am 54ea6c69: (-s ours) Merge remote-tracking branch \'origin/kitkat-dev\'

* commit '54ea6c69d7ca7c5435dcc3d9924ac5fc4f90d180':
  Initial empty repository
diff --git a/COPYING b/COPYING
index f4159e6..9c739c3 100644
--- a/COPYING
+++ b/COPYING
@@ -14,7 +14,7 @@
 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 
+- 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.
diff --git a/LICENSE_PLEASE_READ.txt b/LICENSE_PLEASE_READ.txt
new file mode 100644
index 0000000..bc88efa
--- /dev/null
+++ b/LICENSE_PLEASE_READ.txt
@@ -0,0 +1,22 @@
+Contributions to the collaboration shall not be considered confidential.
+
+Each contributor represents and warrants that it has the right and
+authority to license copyright in its contributions to the collaboration.
+
+Each contributor agrees to license the copyright in the contributions
+under the Modified (2-clause or 3-clause) BSD License or the Clear BSD License.
+
+Please see the IPR statements submitted to the IETF for the complete
+patent licensing details:
+
+Xiph.Org Foundation:
+https://datatracker.ietf.org/ipr/1524/
+
+Microsoft Corporation:
+https://datatracker.ietf.org/ipr/1914/
+
+Skype Limited:
+https://datatracker.ietf.org/ipr/1602/
+
+Broadcom Corporation:
+https://datatracker.ietf.org/ipr/1526/
diff --git a/Makefile.am b/Makefile.am
index 85909ce..edbcc42 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,10 +1,16 @@
+# Provide the full test output for failed tests when using the parallel
+# test suite (which is enabled by default with automake 1.13+).
+export VERBOSE = yes
+
 AUTOMAKE_OPTIONS = subdir-objects
+ACLOCAL_AMFLAGS = -I m4
 
 lib_LTLIBRARIES = libopus.la
 
 DIST_SUBDIRS = doc
 
-INCLUDES = -I$(top_srcdir)/include -I$(top_srcdir)/celt -I$(top_srcdir)/silk -I$(top_srcdir)/silk/float -I$(top_srcdir)/silk/fixed
+AM_CPPFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/celt -I$(top_srcdir)/silk \
+              -I$(top_srcdir)/silk/float -I$(top_srcdir)/silk/fixed
 
 include celt_sources.mk
 include silk_sources.mk
@@ -16,70 +22,84 @@
 SILK_SOURCES += $(SILK_SOURCES_FLOAT)
 endif
 
+OPUS_SOURCES += $(OPUS_SOURCES_FLOAT)
+
+if CPU_ARM
+CELT_SOURCES += $(CELT_SOURCES_ARM)
+endif
+
 include celt_headers.mk
 include silk_headers.mk
 include opus_headers.mk
 
 libopus_la_SOURCES = $(CELT_SOURCES) $(SILK_SOURCES) $(OPUS_SOURCES)
 libopus_la_LDFLAGS = -no-undefined -version-info @OPUS_LT_CURRENT@:@OPUS_LT_REVISION@:@OPUS_LT_AGE@
+libopus_la_LIBADD = $(LIBM)
 
 pkginclude_HEADERS = include/opus.h include/opus_multistream.h include/opus_types.h include/opus_defines.h
 
 noinst_HEADERS = $(OPUS_HEAD) $(SILK_HEAD) $(CELT_HEAD)
 
-noinst_PROGRAMS = opus_demo repacketizer_demo opus_compare tests/test_opus_api tests/test_opus_encode tests/test_opus_decode celt/tests/test_unit_cwrs32 celt/tests/test_unit_dft celt/tests/test_unit_entropy celt/tests/test_unit_laplace celt/tests/test_unit_mathops celt/tests/test_unit_mdct celt/tests/test_unit_rotation celt/tests/test_unit_types
+if EXTRA_PROGRAMS
+noinst_PROGRAMS = opus_demo repacketizer_demo opus_compare tests/test_opus_api tests/test_opus_encode tests/test_opus_decode tests/test_opus_padding celt/tests/test_unit_cwrs32 celt/tests/test_unit_dft celt/tests/test_unit_entropy celt/tests/test_unit_laplace celt/tests/test_unit_mathops celt/tests/test_unit_mdct celt/tests/test_unit_rotation celt/tests/test_unit_types
 
-TESTS = celt/tests/test_unit_types celt/tests/test_unit_mathops celt/tests/test_unit_entropy celt/tests/test_unit_laplace celt/tests/test_unit_dft celt/tests/test_unit_mdct celt/tests/test_unit_rotation celt/tests/test_unit_cwrs32 tests/test_opus_api tests/test_opus_decode tests/test_opus_encode
+TESTS = celt/tests/test_unit_types celt/tests/test_unit_mathops celt/tests/test_unit_entropy celt/tests/test_unit_laplace celt/tests/test_unit_dft celt/tests/test_unit_mdct celt/tests/test_unit_rotation celt/tests/test_unit_cwrs32 tests/test_opus_api tests/test_opus_decode tests/test_opus_encode tests/test_opus_padding
 
 opus_demo_SOURCES = src/opus_demo.c
 
-opus_demo_LDADD = libopus.la -lm
+opus_demo_LDADD = libopus.la $(LIBM)
 
 repacketizer_demo_SOURCES = src/repacketizer_demo.c
 
-repacketizer_demo_LDADD = libopus.la -lm
+repacketizer_demo_LDADD = libopus.la $(LIBM)
 
 opus_compare_SOURCES = src/opus_compare.c
-opus_compare_LDADD = -lm
+opus_compare_LDADD = $(LIBM)
 
 tests_test_opus_api_SOURCES = tests/test_opus_api.c tests/test_opus_common.h
-tests_test_opus_api_LDADD = libopus.la -lm
+tests_test_opus_api_LDADD = libopus.la $(LIBM)
 
 tests_test_opus_encode_SOURCES = tests/test_opus_encode.c tests/test_opus_common.h
-tests_test_opus_encode_LDADD = libopus.la -lm
+tests_test_opus_encode_LDADD = libopus.la $(LIBM)
 
 tests_test_opus_decode_SOURCES = tests/test_opus_decode.c tests/test_opus_common.h
-tests_test_opus_decode_LDADD = libopus.la -lm
+tests_test_opus_decode_LDADD = libopus.la $(LIBM)
+
+tests_test_opus_padding_SOURCES = tests/test_opus_padding.c tests/test_opus_common.h
+tests_test_opus_padding_LDADD = libopus.la $(LIBM)
 
 celt_tests_test_unit_cwrs32_SOURCES = celt/tests/test_unit_cwrs32.c
-celt_tests_test_unit_cwrs32_LDADD = -lm
+celt_tests_test_unit_cwrs32_LDADD = $(LIBM)
 
 celt_tests_test_unit_dft_SOURCES = celt/tests/test_unit_dft.c
-celt_tests_test_unit_dft_LDADD = -lm
+celt_tests_test_unit_dft_LDADD = $(LIBM)
 
 celt_tests_test_unit_entropy_SOURCES = celt/tests/test_unit_entropy.c
-celt_tests_test_unit_entropy_LDADD = -lm
+celt_tests_test_unit_entropy_LDADD = $(LIBM)
 
 celt_tests_test_unit_laplace_SOURCES = celt/tests/test_unit_laplace.c
-celt_tests_test_unit_laplace_LDADD = -lm
+celt_tests_test_unit_laplace_LDADD = $(LIBM)
 
 celt_tests_test_unit_mathops_SOURCES = celt/tests/test_unit_mathops.c
-celt_tests_test_unit_mathops_LDADD = -lm
+celt_tests_test_unit_mathops_LDADD = $(LIBM)
 
 celt_tests_test_unit_mdct_SOURCES = celt/tests/test_unit_mdct.c
-celt_tests_test_unit_mdct_LDADD = -lm
+celt_tests_test_unit_mdct_LDADD = $(LIBM)
 
 celt_tests_test_unit_rotation_SOURCES = celt/tests/test_unit_rotation.c
-celt_tests_test_unit_rotation_LDADD = -lm
+celt_tests_test_unit_rotation_LDADD = $(LIBM)
 
 celt_tests_test_unit_types_SOURCES = celt/tests/test_unit_types.c
-celt_tests_test_unit_types_LDADD = -lm
+celt_tests_test_unit_types_LDADD = $(LIBM)
+endif
 
 if CUSTOM_MODES
 pkginclude_HEADERS += include/opus_custom.h
+if EXTRA_PROGRAMS
 noinst_PROGRAMS += opus_custom_demo
 opus_custom_demo_SOURCES = celt/opus_custom_demo.c
-opus_custom_demo_LDADD = libopus.la -lm
+opus_custom_demo_LDADD = libopus.la $(LIBM)
+endif
 endif
 
 EXTRA_DIST = version.mk \
@@ -88,25 +108,25 @@
              opus.m4 \
              Makefile.unix \
              tests/run_vectors.sh \
-             opus.sln \
-             celt/celt.vcxproj \
-             celt/celt.vcxproj.filters \
-             src/opus_demo.vcxproj \
-             src/opus.vcxproj \
-             src/opus.vcxproj.filters \
-             src/opus_demo.vcxproj.filters \
-             tests/test_opus_decode.vcxproj.filters \
-             tests/test_opus_decode.vcxproj \
-             tests/test_opus_encode.vcxproj.filters \
-             tests/test_opus_encode.vcxproj \
-             tests/test_opus_api.vcxproj.filters \
-             tests/test_opus_api.vcxproj \
-             silk/float/silk_float.vcxproj.filters \
-             silk/float/silk_float.vcxproj \
-             silk/fixed/silk_fixed.vcxproj.filters \
-             silk/fixed/silk_fixed.vcxproj \
-             silk/silk_common.vcxproj \
-             silk/silk_common.vcxproj.filters \
+             win32/VS2010/silk_float.vcxproj \
+             win32/VS2010/celt.vcxproj.filters \
+             win32/VS2010/opus.vcxproj \
+             win32/VS2010/silk_common.vcxproj.filters \
+             win32/VS2010/silk_float.vcxproj.filters \
+             win32/VS2010/test_opus_encode.vcxproj.filters \
+             win32/VS2010/silk_common.vcxproj \
+             win32/VS2010/test_opus_encode.vcxproj \
+             win32/VS2010/opus_demo.vcxproj \
+             win32/VS2010/test_opus_api.vcxproj.filters \
+             win32/VS2010/test_opus_api.vcxproj \
+             win32/VS2010/test_opus_decode.vcxproj.filters \
+             win32/VS2010/silk_fixed.vcxproj.filters \
+             win32/VS2010/opus_demo.vcxproj.filters \
+             win32/VS2010/silk_fixed.vcxproj \
+             win32/VS2010/opus.vcxproj.filters \
+             win32/VS2010/test_opus_decode.vcxproj \
+             win32/VS2010/celt.vcxproj \
+             win32/VS2010/opus.sln \
              win32/genversion.bat \
              win32/config.h
 
@@ -146,4 +166,40 @@
 	( cd doc && $(MAKE) $(AM_MAKEFLAGS) uninstall )
 
 
+# We check this every time make is run, with configure.ac being touched to
+# trigger an update of the build system files if update_version changes the
+# current PACKAGE_VERSION (or if package_version was modified manually by a
+# user with either AUTO_UPDATE=no or no update_version script present - the
+# latter being the normal case for tarball releases).
+#
+# We can't just add the package_version file to CONFIGURE_DEPENDENCIES since
+# simply running autoconf will not actually regenerate configure for us when
+# the content of that file changes (due to autoconf dependency checking not
+# knowing about that without us creating yet another file for it to include).
+#
+# The MAKECMDGOALS check is a gnu-make'ism, but will degrade 'gracefully' for
+# makes that don't support it.  The only loss of functionality is not forcing
+# an update of package_version for `make dist` if AUTO_UPDATE=no, but that is
+# unlikely to be a real problem for any real user.
+$(top_srcdir)/configure.ac: force
+	@case "$(MAKECMDGOALS)" in \
+	    dist-hook)                             exit 0       ;; \
+	    dist-* | dist | distcheck | distclean) _arg=release ;; \
+	esac; \
+	if ! $(top_srcdir)/update_version $$_arg 2> /dev/null; then \
+	    if [ ! -e $(top_srcdir)/package_version ]; then \
+		echo 'PACKAGE_VERSION="unknown"' > $(top_srcdir)/package_version; \
+	    fi; \
+	    . $(top_srcdir)/package_version || exit 1; \
+	    [ "$(PACKAGE_VERSION)" != "$$PACKAGE_VERSION" ] || exit 0; \
+	fi; \
+	touch $@
+
+force:
+
+# Create a minimal package_version file when make dist is run.
+dist-hook:
+	echo 'PACKAGE_VERSION="$(PACKAGE_VERSION)"' > $(top_distdir)/package_version
+
+
 .PHONY: opus check-opus install-opus docs install-docs
diff --git a/Makefile.unix b/Makefile.unix
index 88637c1..c0bab7c 100644
--- a/Makefile.unix
+++ b/Makefile.unix
@@ -20,8 +20,8 @@
 
 ###################### END OF OPTIONS ######################
 
-include version.mk
-CFLAGS += -DOPUS_VERSION='$(OPUS_VERSION)'
+-include package_version
+
 include silk_sources.mk
 include celt_sources.mk
 include opus_sources.mk
@@ -30,6 +30,7 @@
 SILK_SOURCES += $(SILK_SOURCES_FIXED)
 else
 SILK_SOURCES += $(SILK_SOURCES_FLOAT)
+OPUS_SOURCES += $(OPUS_SOURCES_FLOAT)
 endif
 
 EXESUFFIX =
@@ -45,29 +46,19 @@
 cppflags-from-defines   = $(addprefix -D,$(1))
 cppflags-from-includes  = $(addprefix -I,$(1))
 ldflags-from-ldlibdirs  = $(addprefix -L,$(1))
-ldlibs-from-libs                = $(addprefix -l,$(1))
+ldlibs-from-libs        = $(addprefix -l,$(1))
 
 WARNINGS = -Wall -W -Wstrict-prototypes -Wextra -Wcast-align -Wnested-externs -Wshadow
 CFLAGS  += -O2 -g $(WARNINGS) -DOPUS_BUILD
+CINCLUDES = include silk celt
+
 ifdef FIXED_POINT
 CFLAGS += -DFIXED_POINT=1 -DDISABLE_FLOAT_API
+CINCLUDES += silk/fixed
+else
+CINCLUDES += silk/float
 endif
 
-CINCLUDES += include/ \
-	silk/ \
-	silk/float/ \
-	silk/fixed/ \
-	celt/ \
-	src/
-
-# VPATH e.g. VPATH = src:../headers
-VPATH = ./ \
-	silk/interface \
-	silk/src_FIX \
-	silk/src_FLP \
-	silk/src_SigProc_FIX \
-	silk/src_SigProc_FLP \
-	test
 
 LIBS = m
 
@@ -108,9 +99,7 @@
 OPUSCOMPARE_OBJS := $(patsubst %.c,%$(OBJSUFFIX),$(OPUSCOMPARE_SRCS_C))
 
 # Rules
-default: all
-
-all: $(TARGET) lib opus_demo opus_compare
+all: lib opus_demo opus_compare
 
 lib: $(TARGET)
 
@@ -123,5 +112,20 @@
 opus_compare$(EXESUFFIX): $(OPUSCOMPARE_OBJS)
 	$(LINK.o.cmdline)
 
+celt/celt.o: CFLAGS += -DPACKAGE_VERSION='$(PACKAGE_VERSION)'
+celt/celt.o: package_version
+
+package_version: force
+	@if [ -x ./update_version ]; then \
+		./update_version || true; \
+	elif [ ! -e ./package_version ]; then \
+		echo 'PACKAGE_VERSION="unknown"' > ./package_version; \
+	fi
+
+force:
+
 clean:
-	rm -f opus_demo$(EXESUFFIX) opus_compare$(EXESUFFIX) $(TARGET) $(OBJS) $(OPUSDEMO_OBJS)
+	rm -f opus_demo$(EXESUFFIX) opus_compare$(EXESUFFIX) $(TARGET) \
+		$(OBJS) $(OPUSDEMO_OBJS) $(OPUSCOMPARE_OBJS)
+
+.PHONY: all lib clean
diff --git a/README.draft b/README.draft
new file mode 100644
index 0000000..2215966
--- /dev/null
+++ b/README.draft
@@ -0,0 +1,54 @@
+To build this source code, simply type:
+
+% make
+
+If this does not work, or if you want to change the default configuration
+(e.g., to compile for a fixed-point architecture), simply edit the options
+in the Makefile.
+
+An up-to-date implementation conforming to this standard is available in a
+Git repository at git://git.xiph.org/opus.git or on a website at:
+http://opus-codec.org/
+However, although that implementation is expected to remain conformant 
+with the standard, it is the code in this RFC that shall remain normative. 
+To build from the git repository instead of using this RFC, follow these
+steps:
+
+1) Clone the repository (latest implementation of this standard at the time 
+of publication)
+
+% git clone git://git.opus-codec.org/opus.git
+% cd opus
+
+2) Compile
+
+% ./autogen.sh
+% ./configure
+% make
+
+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.
diff --git a/celt/_kiss_fft_guts.h b/celt/_kiss_fft_guts.h
index 33e62c6..f0c6976 100644
--- a/celt/_kiss_fft_guts.h
+++ b/celt/_kiss_fft_guts.h
@@ -94,6 +94,14 @@
     do {(res).r = ADD32((res).r,(a).r);  (res).i = SUB32((res).i,(a).i); \
     }while(0)
 
+#if defined(ARMv4_ASM)
+#include "arm/kiss_fft_armv4.h"
+#endif
+
+#if defined(ARMv5E_ASM)
+#include "arm/kiss_fft_armv5e.h"
+#endif
+
 #else  /* not FIXED_POINT*/
 
 #   define S_MUL(a,b) ( (a)*(b) )
diff --git a/celt/arch.h b/celt/arch.h
index 03cda40..f9c9856 100644
--- a/celt/arch.h
+++ b/celt/arch.h
@@ -100,6 +100,7 @@
 #define DB_SHIFT 10
 
 #define EPSILON 1
+#define VERY_SMALL 0
 #define VERY_LARGE16 ((opus_val16)32767)
 #define Q15_ONE ((opus_val16)32767)
 
@@ -112,10 +113,10 @@
 
 #include "fixed_generic.h"
 
-#ifdef ARM5E_ASM
-#include "fixed_arm5e.h"
-#elif defined (ARM4_ASM)
-#include "fixed_arm4.h"
+#ifdef ARMv5E_ASM
+#include "arm/fixed_armv5e.h"
+#elif defined (ARMv4_ASM)
+#include "arm/fixed_armv4.h"
 #elif defined (BFIN_ASM)
 #include "fixed_bfin.h"
 #elif defined (TI_C5X_ASM)
@@ -140,6 +141,7 @@
 #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)
 
@@ -161,6 +163,7 @@
 #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 HALF16(x)       (.5f*(x))
@@ -182,6 +185,7 @@
 #define MAC16_32_Q15(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))
diff --git a/celt/arm/armcpu.c b/celt/arm/armcpu.c
new file mode 100644
index 0000000..aabcc71
--- /dev/null
+++ b/celt/arm/armcpu.c
@@ -0,0 +1,166 @@
+/* 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"
+
+#define OPUS_CPU_ARM_V4    (1)
+#define OPUS_CPU_ARM_EDSP  (1<<1)
+#define OPUS_CPU_ARM_MEDIA (1<<2)
+#define OPUS_CPU_ARM_NEON  (1<<3)
+
+#if defined(_MSC_VER)
+/*For GetExceptionCode() and EXCEPTION_ILLEGAL_INSTRUCTION.*/
+# define WIN32_LEAN_AND_MEAN
+# define WIN32_EXTRA_LEAN
+# include <windows.h>
+
+static inline opus_uint32 opus_cpu_capabilities(void){
+  opus_uint32 flags;
+  flags=0;
+  /* MSVC has no 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(ARMv5E_ASM)
+  __try{
+    /*PLD [r13]*/
+    __emit(0xF5DDF000);
+    flags|=OPUS_CPU_ARM_EDSP;
+  }
+  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
+    /*Ignore exception.*/
+  }
+#  if defined(ARMv6E_ASM)
+  __try{
+    /*SHADD8 r3,r3,r3*/
+    __emit(0xE6333F93);
+    flags|=OPUS_CPU_ARM_MEDIA;
+  }
+  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
+    /*Ignore exception.*/
+  }
+#   if defined(ARM_HAVE_NEON)
+  __try{
+    /*VORR q0,q0,q0*/
+    __emit(0xF2200150);
+    flags|=OPUS_CPU_ARM_NEON;
+  }
+  __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)
+    {
+      /* 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;
+
+        p = strstr(buf, " neon");
+        if(p != NULL && (p[5] == ' ' || p[5] == '\n'))
+          flags |= OPUS_CPU_ARM_NEON;
+      }
+
+      /* 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;
+      }
+    }
+
+    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))
+    return arch;
+  arch++;
+
+  if(!(flags & OPUS_CPU_ARM_MEDIA))
+    return arch;
+  arch++;
+
+  if(!(flags & OPUS_CPU_ARM_NEON))
+    return arch;
+  arch++;
+
+  return arch;
+}
+
+#endif
diff --git a/celt/arm/armcpu.h b/celt/arm/armcpu.h
new file mode 100644
index 0000000..68d80fe
--- /dev/null
+++ b/celt/arm/armcpu.h
@@ -0,0 +1,35 @@
+/* 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 */
+
+#ifndef ARMCPU_H
+#define ARMCPU_H
+
+int opus_select_arch(void);
+
+#endif
diff --git a/celt/arm/fixed_armv4.h b/celt/arm/fixed_armv4.h
new file mode 100644
index 0000000..bcacc34
--- /dev/null
+++ b/celt/arm/fixed_armv4.h
@@ -0,0 +1,76 @@
+/* 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 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"(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 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"(a<<16)
+  );
+  /*We intentionally don't OR in the high bit of rd_lo for speed.*/
+  return 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))
+
+
+/** 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/celt/arm/fixed_armv5e.h b/celt/arm/fixed_armv5e.h
new file mode 100644
index 0000000..80632c4
--- /dev/null
+++ b/celt/arm/fixed_armv5e.h
@@ -0,0 +1,116 @@
+/* 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 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 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 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 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"(b<<1), "r"(a), "r"(c)
+  );
+  return res;
+}
+#define MAC16_32_Q15(c, a, b) (MAC16_32_Q15_armv5e(c, a, b))
+
+/** 16x16 multiply-add where the result fits in 32 bits */
+#undef MAC16_16
+static 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 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))
+
+#endif
diff --git a/celt/arm/kiss_fft_armv4.h b/celt/arm/kiss_fft_armv4.h
new file mode 100644
index 0000000..e4faad6
--- /dev/null
+++ b/celt/arm/kiss_fft_armv4.h
@@ -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/celt/arm/kiss_fft_armv5e.h b/celt/arm/kiss_fft_armv5e.h
new file mode 100644
index 0000000..9eca183
--- /dev/null
+++ b/celt/arm/kiss_fft_armv5e.h
@@ -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/celt/bands.c b/celt/bands.c
index 3be543c..93bd0bc 100644
--- a/celt/bands.c
+++ b/celt/bands.c
@@ -40,6 +40,23 @@
 #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)
 {
@@ -172,7 +189,8 @@
 #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 celt_ener *bandE, int end, int C, int M)
+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 C, int M)
 {
    int i, c, N;
    const opus_int16 *eBands = m->eBands;
@@ -182,18 +200,39 @@
       celt_sig * OPUS_RESTRICT f;
       const celt_norm * OPUS_RESTRICT x;
       f = freq+c*N;
-      x = X+c*N;
-      for (i=0;i<end;i++)
+      x = X+c*N+M*eBands[start];
+      for (i=0;i<M*eBands[start];i++)
+         *f++ = 0;
+      for (i=start;i<end;i++)
       {
          int j, band_end;
-         opus_val32 g = SHR32(bandE[i+c*m->nbEBands],1);
+         opus_val16 g;
+         opus_val16 lg;
+#ifdef FIXED_POINT
+         int shift;
+#endif
          j=M*eBands[i];
          band_end = M*eBands[i+1];
+         lg = ADD16(bandLogE[i+c*m->nbEBands], SHL16((opus_val16)eMeans[i],6));
+#ifdef FIXED_POINT
+         /* 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));
+         }
+#else
+         g = celt_exp2(lg);
+#endif
          do {
-            *f++ = SHL32(MULT16_32_Q15(*x, g),2);
-            x++;
+            *f++ = SHR32(MULT16_16(*x++, g), shift);
          } while (++j<band_end);
       }
+      celt_assert(start <= end);
       for (i=M*eBands[end];i<N;i++)
          *f++ = 0;
    } while (++c<C);
@@ -345,11 +384,7 @@
    opus_val32 t, lgain, rgain;
 
    /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
-   for (j=0;j<N;j++)
-   {
-      xp = MAC16_16(xp, X[j], Y[j]);
-      side = MAC16_16(side, Y[j], Y[j]);
-   }
+   dual_inner_prod(Y, X, Y, N, &xp, &side);
    /* Compensating for the mid normalization */
    xp = MULT16_32_Q15(mid, xp);
    /* mid and side are in Q15, not Q14 like X and Y */
@@ -483,50 +518,6 @@
    return decision;
 }
 
-#ifdef MEASURE_NORM_MSE
-
-float MSE[30] = {0};
-int nbMSEBands = 0;
-int MSECount[30] = {0};
-
-void dump_norm_mse(void)
-{
-   int i;
-   for (i=0;i<nbMSEBands;i++)
-   {
-      printf ("%g ", MSE[i]/MSECount[i]);
-   }
-   printf ("\n");
-}
-
-void measure_norm_mse(const CELTMode *m, float *X, float *X0, float *bandE, float *bandE0, int M, int N, int C)
-{
-   static int init = 0;
-   int i;
-   if (!init)
-   {
-      atexit(dump_norm_mse);
-      init = 1;
-   }
-   for (i=0;i<m->nbEBands;i++)
-   {
-      int j;
-      int c;
-      float g;
-      if (bandE0[i]<10 || (C==2 && bandE0[i+m->nbEBands]<1))
-         continue;
-      c=0; do {
-         g = bandE[i+c*m->nbEBands]/(1e-15+bandE0[i+c*m->nbEBands]);
-         for (j=M*m->eBands[i];j<M*m->eBands[i+1];j++)
-            MSE[i] += (g*X[j+c*N]-X0[j+c*N])*(g*X[j+c*N]-X0[j+c*N]);
-      } while (++c<C);
-      MSECount[i]+=C;
-   }
-   nbMSEBands = m->nbEBands;
-}
-
-#endif
-
 /* 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
@@ -629,289 +620,304 @@
    return qn;
 }
 
-/* This function is responsible for encoding and decoding a band for both
-   the mono and stereo case. Even in the mono case, 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_band(int encode, const CELTMode *m, int i, celt_norm *X, celt_norm *Y,
-      int N, int b, int spread, int B, int intensity, int tf_change, celt_norm *lowband, ec_ctx *ec,
-      opus_int32 *remaining_bits, int LM, celt_norm *lowband_out, const celt_ener *bandE, int level,
-      opus_uint32 *seed, opus_val16 gain, celt_norm *lowband_scratch, int fill)
+struct band_ctx {
+   int encode;
+   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;
+};
+
+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);
+   }
+   tell = ec_tell_frac(ec);
+   if (qn!=1)
+   {
+      if (encode)
+         itheta = (itheta*qn+8192)>>14;
+
+      /* 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);
+         }
+      }
+      itheta = (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;
+         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;
+      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)
+{
+#ifdef RESYNTH
+   int resynth = 1;
+#else
+   int resynth = !ctx->encode;
+#endif
+   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 (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 stereo, split;
    int imid=0, iside=0;
-   int N0=N;
    int N_B=N;
-   int N_B0;
    int B0=B;
-   int time_divide=0;
-   int recombine=0;
-   int inv = 0;
    opus_val16 mid=0, side=0;
-   int longBlocks;
    unsigned cm=0;
 #ifdef RESYNTH
    int resynth = 1;
 #else
-   int resynth = !encode;
+   int resynth = !ctx->encode;
 #endif
+   celt_norm *Y=NULL;
+   int encode;
+   const CELTMode *m;
+   int i;
+   int spread;
+   ec_ctx *ec;
 
-   longBlocks = B0==1;
+   encode = ctx->encode;
+   m = ctx->m;
+   i = ctx->i;
+   spread = ctx->spread;
+   ec = ctx->ec;
 
    N_B /= B;
-   N_B0 = N_B;
-
-   split = stereo = Y != NULL;
-
-   /* Special case for one sample */
-   if (N==1)
-   {
-      int c;
-      celt_norm *x = X;
-      c=0; do {
-         int sign=0;
-         if (*remaining_bits>=1<<BITRES)
-         {
-            if (encode)
-            {
-               sign = x[0]<0;
-               ec_enc_bits(ec, sign, 1);
-            } else {
-               sign = ec_dec_bits(ec, 1);
-            }
-            *remaining_bits -= 1<<BITRES;
-            b-=1<<BITRES;
-         }
-         if (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;
-   }
-
-   if (!stereo && level == 0)
-   {
-      int k;
-      if (tf_change>0)
-         recombine = tf_change;
-      /* Band recombining to increase frequency resolution */
-
-      if (lowband && (recombine || ((N_B&1) == 0 && tf_change<0) || B0>1))
-      {
-         int j;
-         for (j=0;j<N;j++)
-            lowband_scratch[j] = lowband[j];
-         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);
-      }
-   }
 
    /* 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 (!stereo && LM != -1 && b > cache[cache[0]]+12 && N>2)
+   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;
-      split = 1;
       LM -= 1;
       if (B==1)
          fill = (fill&1)|(fill<<1);
       B = (B+1)>>1;
-   }
 
-   if (split)
-   {
-      int qn;
-      int itheta=0;
-      int mbits, sbits, delta;
-      int qalloc;
-      int pulse_cap;
-      int offset;
-      int orig_fill;
-      opus_int32 tell;
-
-      /* 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);
-      }
-      tell = ec_tell_frac(ec);
-      if (qn!=1)
-      {
-         if (encode)
-            itheta = (itheta*qn+8192)>>14;
-
-         /* 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);
-            }
-         }
-         itheta = (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;
-            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 && *remaining_bits > 2<<BITRES)
-         {
-            if (encode)
-               ec_enc_bit_logp(ec, inv, 2);
-            else
-               inv = ec_dec_bit_logp(ec, 2);
-         } else
-            inv = 0;
-         itheta = 0;
-      }
-      qalloc = ec_tell_frac(ec) - tell;
-      b -= qalloc;
-
-      orig_fill = fill;
-      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));
-      }
-
+      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;
@@ -920,136 +926,59 @@
       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 && stereo)
+      /* Give more bits to low-energy MDCTs than they would otherwise deserve */
+      if (B0>1 && (itheta&0x3fff))
       {
-         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;
-         *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(encode, m, i, x2, NULL, N, mbits, spread, B, intensity, tf_change, lowband, ec, remaining_bits, LM, lowband_out, NULL, level, seed, gain, 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 (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 */
-         celt_norm *next_lowband2=NULL;
-         celt_norm *next_lowband_out1=NULL;
-         int next_level=0;
-         opus_int32 rebalance;
-
-         /* Give more bits to low-energy MDCTs than they would otherwise deserve */
-         if (B0>1 && !stereo && (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;
-         *remaining_bits -= qalloc;
-
-         if (lowband && !stereo)
-            next_lowband2 = lowband+N; /* >32-bit split case */
-
-         /* Only stereo needs to pass on lowband_out. Otherwise, it's
-            handled at the end */
-         if (stereo)
-            next_lowband_out1 = lowband_out;
+         if (itheta > 8192)
+            /* Rough approximation for pre-echo masking */
+            delta -= delta>>(4-LM);
          else
-            next_level = level+1;
-
-         rebalance = *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(encode, m, i, X, NULL, N, mbits, spread, B, intensity, tf_change,
-                  lowband, ec, remaining_bits, LM, next_lowband_out1,
-                  NULL, next_level, seed, stereo ? Q15ONE : MULT16_16_P15(gain,mid), lowband_scratch, fill);
-            rebalance = mbits - (rebalance-*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(encode, m, i, Y, NULL, N, sbits, spread, B, intensity, tf_change,
-                  next_lowband2, ec, remaining_bits, LM, NULL,
-                  NULL, next_level, seed, MULT16_16_P15(gain,side), NULL, fill>>B)<<((B0>>1)&(stereo-1));
-         } 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(encode, m, i, Y, NULL, N, sbits, spread, B, intensity, tf_change,
-                  next_lowband2, ec, remaining_bits, LM, NULL,
-                  NULL, next_level, seed, MULT16_16_P15(gain,side), NULL, fill>>B)<<((B0>>1)&(stereo-1));
-            rebalance = sbits - (rebalance-*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(encode, m, i, X, NULL, N, mbits, spread, B, intensity, tf_change,
-                  lowband, ec, remaining_bits, LM, next_lowband_out1,
-                  NULL, next_level, seed, stereo ? Q15ONE : MULT16_16_P15(gain,mid), lowband_scratch, fill);
-         }
+            /* 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);
-      *remaining_bits -= curr_bits;
+      ctx->remaining_bits -= curr_bits;
 
       /* Ensures we can never bust the budget */
-      while (*remaining_bits < 0 && q > 0)
+      while (ctx->remaining_bits < 0 && q > 0)
       {
-         *remaining_bits += curr_bits;
+         ctx->remaining_bits += curr_bits;
          q--;
          curr_bits = pulses2bits(m, i, LM, q);
-         *remaining_bits -= curr_bits;
+         ctx->remaining_bits -= curr_bits;
       }
 
       if (q!=0)
@@ -1073,7 +1002,7 @@
          if (resynth)
          {
             unsigned cm_mask;
-            /*B can be as large as 16, so this shift might overflow an int on a
+            /* 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;
@@ -1087,8 +1016,8 @@
                   /* Noise */
                   for (j=0;j<N;j++)
                   {
-                     *seed = celt_lcg_rand(*seed);
-                     X[j] = (celt_norm)((opus_int32)*seed>>20);
+                     ctx->seed = celt_lcg_rand(ctx->seed);
+                     X[j] = (celt_norm)((opus_int32)ctx->seed>>20);
                   }
                   cm = cm_mask;
                } else {
@@ -1096,10 +1025,10 @@
                   for (j=0;j<N;j++)
                   {
                      opus_val16 tmp;
-                     *seed = celt_lcg_rand(*seed);
+                     ctx->seed = celt_lcg_rand(ctx->seed);
                      /* About 48 dB below the "normal" folding level */
                      tmp = QCONST16(1.0f/256, 10);
-                     tmp = (*seed)&0x8000 ? tmp : -tmp;
+                     tmp = (ctx->seed)&0x8000 ? tmp : -tmp;
                      X[j] = lowband[j]+tmp;
                   }
                   cm = fill;
@@ -1110,64 +1039,307 @@
       }
    }
 
+   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;
+#ifdef RESYNTH
+   int resynth = 1;
+#else
+   int resynth = !ctx->encode;
+#endif
+   int k;
+   int encode;
+   int tf_change;
+
+   encode = ctx->encode;
+   tf_change = ctx->tf_change;
+
+   longBlocks = B0==1;
+
+   N_B /= B;
+   N_B0 = N_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))
+   {
+      int j;
+      for (j=0;j<N;j++)
+         lowband_scratch[j] = lowband[j];
+      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 (resynth)
    {
-      if (stereo)
+      /* 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++)
       {
-         if (N!=2)
-            stereo_merge(X, Y, mid, N);
-         if (inv)
-         {
-            int j;
-            for (j=0;j<N;j++)
-               Y[j] = -Y[j];
-         }
-      } else if (level == 0)
+         B >>= 1;
+         N_B <<= 1;
+         cm |= cm>>B;
+         haar1(X, N_B, B);
+      }
+
+      for (k=0;k<recombine;k++)
       {
-         int 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;
 
-         /* Undo the sample reorganization going from time order to frequency order */
-         if (B0>1)
-            interleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
+      /* 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;
+}
 
-         /* Undo time-freq changes that we did earlier */
-         N_B = N_B0;
-         B = B0;
-         for (k=0;k<time_divide;k++)
+
+/* 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;
+#ifdef RESYNTH
+   int resynth = 1;
+#else
+   int resynth = !ctx->encode;
+#endif
+   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)
          {
-            B >>= 1;
-            N_B <<= 1;
-            cm |= cm>>B;
-            haar1(X, N_B, B);
+            /* 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 (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;
 
-         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;
+      mbits = IMAX(0, IMIN(b, (b-delta)/2));
+      sbits = b-mbits;
+      ctx->remaining_bits -= qalloc;
 
-         /* 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;
+      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 (resynth)
+   {
+      if (N!=2)
+         stereo_merge(X, Y, mid, N);
+      if (inv)
+      {
+         int j;
+         for (j=0;j<N;j++)
+            Y[j] = -Y[j];
       }
    }
    return cm;
 }
 
+
 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,
@@ -1178,27 +1350,41 @@
    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);
+   celt_norm *lowband_scratch;
    int B;
    int M;
    int lowband_offset;
    int update_lowband = 1;
    int C = Y_ != NULL ? 2 : 1;
+   int norm_offset;
 #ifdef RESYNTH
    int resynth = 1;
 #else
    int resynth = !encode;
 #endif
+   struct band_ctx ctx;
    SAVE_STACK;
 
    M = 1<<LM;
    B = shortBlocks ? M : 1;
-   ALLOC(_norm, C*M*eBands[m->nbEBands], celt_norm);
-   ALLOC(lowband_scratch, M*(eBands[m->nbEBands]-eBands[m->nbEBands-1]), celt_norm);
+   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];
+   norm2 = norm + M*eBands[m->nbEBands-1]-norm_offset;
+   /* We can use the last band as scratch space because we don't need that
+      scratch space for the last band. */
+   lowband_scratch = X_+M*eBands[m->nbEBands-1];
 
    lowband_offset = 0;
+   ctx.bandE = bandE;
+   ctx.ec = ec;
+   ctx.encode = encode;
+   ctx.intensity = intensity;
+   ctx.m = m;
+   ctx.seed = *seed;
+   ctx.spread = spread;
    for (i=start;i<end;i++)
    {
       opus_int32 tell;
@@ -1210,6 +1396,10 @@
       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)
@@ -1223,6 +1413,7 @@
       if (i != start)
          balance -= tell;
       remaining_bits = total_bits-tell-1;
+      ctx.remaining_bits = remaining_bits;
       if (i <= codedBands-1)
       {
          curr_balance = balance / IMIN(3, codedBands-i);
@@ -1235,26 +1426,30 @@
             lowband_offset = i;
 
       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 (i==end-1)
+         lowband_scratch = NULL;
 
       /* Get a conservative estimate of the collapse_mask's for the bands we're
-          going to be folding from. */
+         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(M*eBands[start], M*eBands[lowband_offset]-N);
+         effective_lowband = IMAX(0, M*eBands[lowband_offset]-norm_offset-N);
          fold_start = lowband_offset;
-         while(M*eBands[--fold_start] > effective_lowband);
+         while(M*eBands[--fold_start] > effective_lowband+norm_offset);
          fold_end = lowband_offset-1;
-         while(M*eBands[++fold_end] < effective_lowband+N);
+         while(M*eBands[++fold_end] < effective_lowband+norm_offset+N);
          x_cm = y_cm = 0;
          fold_i = fold_start; do {
            x_cm |= collapse_masks[fold_i*C+0];
@@ -1262,7 +1457,7 @@
          } while (++fold_i<fold_end);
       }
       /* Otherwise, we'll be using the LCG to fold, so all blocks will (almost
-          always) be non-zero.*/
+         always) be non-zero. */
       else
          x_cm = y_cm = (1<<B)-1;
 
@@ -1270,33 +1465,42 @@
       {
          int j;
 
-         /* Switch off dual stereo to do intensity */
+         /* Switch off dual stereo to do intensity. */
          dual_stereo = 0;
          if (resynth)
-            for (j=M*eBands[start];j<M*eBands[i];j++)
+            for (j=0;j<M*eBands[i]-norm_offset;j++)
                norm[j] = HALF32(norm[j]+norm2[j]);
       }
       if (dual_stereo)
       {
-         x_cm = quant_band(encode, m, i, X, NULL, N, b/2, spread, B, intensity, tf_change,
-               effective_lowband != -1 ? norm+effective_lowband : NULL, ec, &remaining_bits, LM,
-               norm+M*eBands[i], bandE, 0, seed, Q15ONE, lowband_scratch, x_cm);
-         y_cm = quant_band(encode, m, i, Y, NULL, N, b/2, spread, B, intensity, tf_change,
-               effective_lowband != -1 ? norm2+effective_lowband : NULL, ec, &remaining_bits, LM,
-               norm2+M*eBands[i], bandE, 0, seed, Q15ONE, lowband_scratch, y_cm);
+         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 {
-         x_cm = quant_band(encode, m, i, X, Y, N, b, spread, B, intensity, tf_change,
-               effective_lowband != -1 ? norm+effective_lowband : NULL, ec, &remaining_bits, LM,
-               norm+M*eBands[i], bandE, 0, seed, Q15ONE, lowband_scratch, x_cm|y_cm);
+         if (Y!=NULL)
+         {
+            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 the folding position only as long as we have 1 bit/sample depth. */
       update_lowband = b>(N<<BITRES);
    }
+   *seed = ctx.seed;
+
    RESTORE_STACK;
 }
 
diff --git a/celt/bands.h b/celt/bands.h
index 9ff8ffd..96ba52a 100644
--- a/celt/bands.h
+++ b/celt/bands.h
@@ -39,7 +39,7 @@
 /** Compute the amplitude (sqrt energy) in each of the bands
  * @param m Mode data
  * @param X Spectrum
- * @param bands Square root of the energy for each band (returned)
+ * @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 M);
 
@@ -49,16 +49,17 @@
     equal to 1
  * @param m Mode data
  * @param X Spectrum (returned normalised)
- * @param bands Square root of the energy for each band
+ * @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 bands Square root of the energy for each band
+ * @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 celt_ener *bandE, int end, int C, int M);
+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 C, int M);
 
 #define SPREAD_NONE       (0)
 #define SPREAD_LIGHT      (1)
@@ -76,14 +77,30 @@
 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 enc Entropy encoder
+ * @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
  */
 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 time_domain, int fold, int dual_stereo, int intensity, int *tf_res,
+      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);
 
 void anti_collapse(const CELTMode *m, celt_norm *X_, unsigned char *collapse_masks, int LM, int C, int size,
@@ -92,4 +109,6 @@
 
 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/celt/celt.c b/celt/celt.c
index 9bbe852..3e0ce6e 100644
--- a/celt/celt.c
+++ b/celt/celt.c
@@ -50,62 +50,12 @@
 #include "celt_lpc.h"
 #include "vq.h"
 
-#ifndef OPUS_VERSION
-#define OPUS_VERSION "unknown"
+#ifndef PACKAGE_VERSION
+#define PACKAGE_VERSION "unknown"
 #endif
 
-#ifdef CUSTOM_MODES
-#define OPUS_CUSTOM_NOSTATIC
-#else
-#define OPUS_CUSTOM_NOSTATIC static 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 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 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
-
-static int resampling_factor(opus_int32 rate)
+int resampling_factor(opus_int32 rate)
 {
    int ret;
    switch (rate)
@@ -135,658 +85,101 @@
    return ret;
 }
 
-/** Encoder state
- @brief Encoder state
- */
-struct OpusCustomEncoder {
-   const OpusCustomMode *mode;     /**< Mode used by the encoder */
-   int overlap;
-   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;
-
-   /* 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;
-
-   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;
-
-#ifdef RESYNTH
-   celt_sig syn_mem[2][2*MAX_PERIOD];
-#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 */
-#ifdef RESYNTH
-   /* opus_val16 overlap_mem[],  Size = channels*overlap */
-#endif
-};
-
-int celt_encoder_get_size(int channels)
+#ifndef OVERRIDE_COMB_FILTER_CONST
+static void comb_filter_const(opus_val32 *y, opus_val32 *x, int T, int N,
+      opus_val16 g10, opus_val16 g11, opus_val16 g12)
 {
-   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]; */
-         + 3*channels*mode->nbEBands*sizeof(opus_val16);  /* opus_val16 oldBandE[channels*mode->nbEBands]; */
-                                                          /* opus_val16 oldLogE[channels*mode->nbEBands]; */
-                                                          /* opus_val16 oldLogE2[channels*mode->nbEBands]; */
-#ifdef RESYNTH
-   size += channels*mode->overlap*sizeof(celt_sig);       /* celt_sig overlap_mem[channels*mode->nbEBands]; */
-#endif
-   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 */
-
-int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels)
-{
-   int ret;
-   ret = opus_custom_encoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
-   if (ret != OPUS_OK)
-      return ret;
-   st->upsample = resampling_factor(sampling_rate);
-   return OPUS_OK;
-}
-
-OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
-{
-   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->overlap = mode->overlap;
-   st->stream_channels = st->channels = channels;
-
-   st->upsample = 1;
-   st->start = 0;
-   st->end = st->mode->effEBands;
-   st->signalling = 1;
-
-   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
-void opus_custom_encoder_destroy(CELTEncoder *st)
-{
-   opus_free(st);
-}
-#endif /* CUSTOM_MODES */
-
-static inline opus_val16 SIG2WORD16(celt_sig x)
-{
-#ifdef FIXED_POINT
-   x = PSHR32(x, SIG_SHIFT);
-   x = MAX32(x, -32768);
-   x = MIN32(x, 32767);
-   return EXTRACT16(x);
-#else
-   return (opus_val16)x;
-#endif
-}
-
-static int transient_analysis(const opus_val32 * OPUS_RESTRICT in, int len, int C,
-                              int overlap)
-{
+   opus_val32 x0, x1, x2, x3, x4;
    int i;
-   VARDECL(opus_val16, tmp);
-   opus_val32 mem0=0,mem1=0;
-   int is_transient = 0;
-   int block;
-   int N;
-   VARDECL(opus_val16, bins);
-   SAVE_STACK;
-   ALLOC(tmp, len, opus_val16);
-
-   block = overlap/2;
-   N=len/block;
-   ALLOC(bins, N, opus_val16);
-   if (C==1)
-   {
-      for (i=0;i<len;i++)
-         tmp[i] = SHR32(in[i],SIG_SHIFT);
-   } else {
-      for (i=0;i<len;i++)
-         tmp[i] = SHR32(ADD32(in[i],in[i+len]), SIG_SHIFT+1);
-   }
-
-   /* 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 = tmp[i];
-      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] = EXTRACT16(SHR32(y,2));
-   }
-   /* First few samples are bad because we don't propagate the memory */
-   for (i=0;i<12;i++)
-      tmp[i] = 0;
-
+   x4 = x[-T-2];
+   x3 = x[-T-1];
+   x2 = x[-T];
+   x1 = x[-T+1];
    for (i=0;i<N;i++)
    {
-      int j;
-      opus_val16 max_abs=0;
-      for (j=0;j<block;j++)
-         max_abs = MAX16(max_abs, ABS16(tmp[i*block+j]));
-      bins[i] = max_abs;
+      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));
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
    }
-   for (i=0;i<N;i++)
-   {
-      int j;
-      int conseq=0;
-      opus_val16 t1, t2, t3;
 
-      t1 = MULT16_16_Q15(QCONST16(.15f, 15), bins[i]);
-      t2 = MULT16_16_Q15(QCONST16(.4f, 15), bins[i]);
-      t3 = MULT16_16_Q15(QCONST16(.15f, 15), bins[i]);
-      for (j=0;j<i;j++)
-      {
-         if (bins[j] < t1)
-            conseq++;
-         if (bins[j] < t2)
-            conseq++;
-         else
-            conseq = 0;
-      }
-      if (conseq>=3)
-         is_transient=1;
-      conseq = 0;
-      for (j=i+1;j<N;j++)
-      {
-         if (bins[j] < t3)
-            conseq++;
-         else
-            conseq = 0;
-      }
-      if (conseq>=7)
-         is_transient=1;
-   }
-   RESTORE_STACK;
-#ifdef FUZZING
-   is_transient = rand()&0x1;
+}
 #endif
-   return is_transient;
-}
 
-/** 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 LM)
-{
-   if (C==1 && !shortBlocks)
-   {
-      const int overlap = OVERLAP(mode);
-      clt_mdct_forward(&mode->mdct, in, out, mode->window, overlap, mode->maxLM-LM, 1);
-   } else {
-      const int overlap = OVERLAP(mode);
-      int N = mode->shortMdctSize<<LM;
-      int B = 1;
-      int b, c;
-      if (shortBlocks)
-      {
-         N = mode->shortMdctSize;
-         B = shortBlocks;
-      }
-      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, shortBlocks ? mode->maxLM : mode->maxLM-LM, B);
-         }
-      } while (++c<C);
-   }
-}
-
-/** Compute the IMDCT and apply window for all sub-frames and
-    all channels in a frame */
-static void compute_inv_mdcts(const CELTMode *mode, int shortBlocks, celt_sig *X,
-      celt_sig * OPUS_RESTRICT out_mem[],
-      celt_sig * OPUS_RESTRICT overlap_mem[], int C, int LM)
-{
-   int c;
-   const int N = mode->shortMdctSize<<LM;
-   const int overlap = OVERLAP(mode);
-   VARDECL(opus_val32, x);
-   SAVE_STACK;
-
-   ALLOC(x, N+overlap, opus_val32);
-   c=0; do {
-      int j;
-      int b;
-      int N2 = N;
-      int B = 1;
-
-      if (shortBlocks)
-      {
-         N2 = mode->shortMdctSize;
-         B = shortBlocks;
-      }
-      /* Prevents problems from the imdct doing the overlap-add */
-      OPUS_CLEAR(x, overlap);
-
-      for (b=0;b<B;b++)
-      {
-         /* IMDCT on the interleaved the sub-frames */
-         clt_mdct_backward(&mode->mdct, &X[b+c*N2*B], x+N2*b, mode->window, overlap, shortBlocks ? mode->maxLM : mode->maxLM-LM, B);
-      }
-
-      for (j=0;j<overlap;j++)
-         out_mem[c][j] = x[j] + overlap_mem[c][j];
-      for (;j<N;j++)
-         out_mem[c][j] = x[j];
-      for (j=0;j<overlap;j++)
-         overlap_mem[c][j] = x[N+j];
-   } while (++c<C);
-   RESTORE_STACK;
-}
-
-static void deemphasis(celt_sig *in[], opus_val16 *pcm, int N, int C, int downsample, const opus_val16 *coef, celt_sig *mem)
-{
-   int c;
-   int count=0;
-   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;
-      for (j=0;j<N;j++)
-      {
-         celt_sig tmp = *x + m;
-         m = MULT16_32_Q15(coef[0], tmp)
-           - MULT16_32_Q15(coef[1], *x);
-         tmp = SHL32(MULT16_32_Q15(coef[3], tmp), 2);
-         x++;
-         /* Technically the store could be moved outside of the if because
-            the stores we don't want will just be overwritten */
-         if (count==0)
-            *y = SCALEOUT(SIG2WORD16(tmp));
-         if (++count==downsample)
-         {
-            y+=C;
-            count=0;
-         }
-      }
-      mem[c] = m;
-   } while (++c<C);
-}
-
-static void comb_filter(opus_val32 *y, opus_val32 *x, int T0, int T1, int N,
+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 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;
+   }
    g00 = MULT16_16_Q15(g0, gains[tapset0][0]);
    g01 = MULT16_16_Q15(g0, gains[tapset0][1]);
    g02 = MULT16_16_Q15(g0, gains[tapset0][2]);
    g10 = MULT16_16_Q15(g1, gains[tapset1][0]);
    g11 = MULT16_16_Q15(g1, gains[tapset1][1]);
    g12 = MULT16_16_Q15(g1, gains[tapset1][2]);
+   x1 = x[-T1+1];
+   x2 = x[-T1  ];
+   x3 = x[-T1-1];
+   x4 = x[-T1-2];
    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),x[i-T0-1])
-               + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g01),x[i-T0+1])
-               + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),x[i-T0-2])
-               + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),x[i-T0+2])
-               + MULT16_32_Q15(MULT16_16_Q15(f,g10),x[i-T1])
-               + MULT16_32_Q15(MULT16_16_Q15(f,g11),x[i-T1-1])
-               + MULT16_32_Q15(MULT16_16_Q15(f,g11),x[i-T1+1])
-               + MULT16_32_Q15(MULT16_16_Q15(f,g12),x[i-T1-2])
-               + MULT16_32_Q15(MULT16_16_Q15(f,g12),x[i-T1+2]);
+               + 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));
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
 
    }
-   for (i=overlap;i<N;i++)
-      y[i] = x[i]
-               + MULT16_32_Q15(g10,x[i-T1])
-               + MULT16_32_Q15(g11,x[i-T1-1])
-               + MULT16_32_Q15(g11,x[i-T1+1])
-               + MULT16_32_Q15(g12,x[i-T1-2])
-               + MULT16_32_Q15(g12,x[i-T1+2]);
+   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);
 }
 
-static const signed char tf_select_table[4][8] = {
+const signed char tf_select_table[4][8] = {
       {0, -1, 0, -1,    0,-1, 0,-1},
       {0, -1, 0, -2,    1, 0, 1,-1},
       {0, -2, 0, -3,    2, 0, 1,-1},
       {0, -2, 0, -3,    3, 0, 1,-1},
 };
 
-static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, int width)
-{
-   int i, j;
-   static const opus_val16 sqrtM_1[4] = {Q15ONE, QCONST16(.70710678f,15), QCONST16(0.5f,15), QCONST16(0.35355339f,15)};
-   opus_val32 L1;
-   opus_val16 bias;
-   L1=0;
-   for (i=0;i<1<<LM;i++)
-   {
-      opus_val32 L2 = 0;
-      for (j=0;j<N>>LM;j++)
-         L2 = MAC16_16(L2, tmp[(j<<LM)+i], tmp[(j<<LM)+i]);
-      L1 += celt_sqrt(L2);
-   }
-   L1 = MULT16_32_Q15(sqrtM_1[LM], L1);
-   if (width==1)
-      bias = QCONST16(.12f,15)*LM;
-   else if (width==2)
-      bias = QCONST16(.05f,15)*LM;
-   else
-      bias = QCONST16(.02f,15)*LM;
-   L1 = MAC16_32_Q15(L1, bias, L1);
-   return L1;
-}
 
-static int tf_analysis(const CELTMode *m, int len, int C, int isTransient,
-      int *tf_res, int nbCompressedBytes, celt_norm *X, int N0, int LM,
-      int start, int *tf_sum)
-{
-   int i;
-   VARDECL(int, metric);
-   int cost0;
-   int cost1;
-   VARDECL(int, path0);
-   VARDECL(int, path1);
-   VARDECL(celt_norm, tmp);
-   int lambda;
-   int tf_select=0;
-   SAVE_STACK;
-
-   if (nbCompressedBytes<15*C || start!=0)
-   {
-      *tf_sum = 0;
-      for (i=0;i<len;i++)
-         tf_res[i] = isTransient;
-      return 0;
-   }
-   if (nbCompressedBytes<40)
-      lambda = 12;
-   else if (nbCompressedBytes<60)
-      lambda = 6;
-   else if (nbCompressedBytes<100)
-      lambda = 4;
-   else
-      lambda = 3;
-
-   ALLOC(metric, len, int);
-   ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
-   ALLOC(path0, len, int);
-   ALLOC(path1, len, int);
-
-   *tf_sum = 0;
-   for (i=0;i<len;i++)
-   {
-      int j, k, N;
-      opus_val32 L1, best_L1;
-      int best_level=0;
-      N = (m->eBands[i+1]-m->eBands[i])<<LM;
-      for (j=0;j<N;j++)
-         tmp[j] = X[j+(m->eBands[i]<<LM)];
-      /* 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, N>>LM);
-      best_L1 = L1;
-      /*printf ("%f ", L1);*/
-      for (k=0;k<LM;k++)
-      {
-         int B;
-
-         if (isTransient)
-            B = (LM-k-1);
-         else
-            B = k+1;
-
-         if (isTransient)
-            haar1(tmp, N>>(LM-k), 1<<(LM-k));
-         else
-            haar1(tmp, N>>k, 1<<k);
-
-         L1 = l1_metric(tmp, N, B, N>>LM);
-
-         if (L1 < best_L1)
-         {
-            best_L1 = L1;
-            best_level = k+1;
-         }
-      }
-      /*printf ("%d ", isTransient ? LM-best_level : best_level);*/
-      if (isTransient)
-         metric[i] = best_level;
-      else
-         metric[i] = -best_level;
-      *tf_sum += metric[i];
-   }
-   /*printf("\n");*/
-   /* NOTE: Future optimized implementations could detect extreme transients and set
-      tf_select = 1 but so far we have not found a reliable way of making this useful */
-   tf_select = 0;
-
-   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]-tf_select_table[LM][4*isTransient+2*tf_select+0]);
-      cost1 = curr1 + abs(metric[i]-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];
-   }
-   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]];
-   /*printf("%d %d ", isTransient, tf_select); for(i=0;i<end;i++)printf("%d ", tf_res[i]);printf("\n");*/
-}
-
-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]];
-   }
-}
-
-static void init_caps(const CELTMode *m,int *cap,int LM,int C)
+void init_caps(const CELTMode *m,int *cap,int LM,int C)
 {
    int i;
    for (i=0;i<m->nbEBands;i++)
@@ -797,2082 +190,6 @@
    }
 }
 
-static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X,
-      const opus_val16 *bandLogE, int end, int LM, int C, int N0)
-{
-   int i;
-   opus_val32 diff=0;
-   int c;
-   int trim_index = 5;
-   if (C==2)
-   {
-      opus_val16 sum = 0; /* Q10 */
-      /* Compute inter-channel correlation for low frequencies */
-      for (i=0;i<8;i++)
-      {
-         int j;
-         opus_val32 partial = 0;
-         for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
-            partial = MAC16_16(partial, X[j], X[N0+j]);
-         sum = ADD16(sum, EXTRACT16(SHR32(partial, 18)));
-      }
-      sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum);
-      /*printf ("%f\n", sum);*/
-      if (sum > QCONST16(.995f,10))
-         trim_index-=4;
-      else if (sum > QCONST16(.92f,10))
-         trim_index-=3;
-      else if (sum > QCONST16(.85f,10))
-         trim_index-=2;
-      else if (sum > QCONST16(.8f,10))
-         trim_index-=1;
-   }
-
-   /* Estimate spectral tilt */
-   c=0; do {
-      for (i=0;i<end-1;i++)
-      {
-         diff += bandLogE[i+c*m->nbEBands]*(opus_int32)(2+2*i-m->nbEBands);
-      }
-   } while (++c<C);
-   /* We divide by two here to avoid making the tilt larger for stereo as a
-      result of a bug in the loop above */
-   diff /= 2*C*(end-1);
-   /*printf("%f\n", diff);*/
-   if (diff > QCONST16(2.f, DB_SHIFT))
-      trim_index--;
-   if (diff > QCONST16(8.f, DB_SHIFT))
-      trim_index--;
-   if (diff < -QCONST16(4.f, DB_SHIFT))
-      trim_index++;
-   if (diff < -QCONST16(10.f, DB_SHIFT))
-      trim_index++;
-
-   if (trim_index<0)
-      trim_index = 0;
-   if (trim_index>10)
-      trim_index = 10;
-#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);
-}
-
-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(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;
-   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 effEnd;
-   int codedBands;
-   int tf_sum;
-   int alloc_trim;
-   int pitch_index=COMBFILTER_MINPERIOD;
-   opus_val16 gain1 = 0;
-   int intensity=0;
-   int dual_stereo=0;
-   int effectiveBytes;
-   opus_val16 pf_threshold;
-   int dynalloc_logp;
-   opus_int32 vbr_rate;
-   opus_int32 total_bits;
-   opus_int32 total_boost;
-   opus_int32 balance;
-   opus_int32 tell;
-   int prefilter_tapset=0;
-   int pf_on;
-   int anti_collapse_rsv;
-   int anti_collapse_on=0;
-   int silence=0;
-   ALLOC_STACK;
-
-   if (nbCompressedBytes<2 || pcm==NULL)
-     return OPUS_BAD_ARG;
-
-   frame_size *= st->upsample;
-   for (LM=0;LM<=st->mode->maxLM;LM++)
-      if (st->mode->shortMdctSize<<LM==frame_size)
-         break;
-   if (LM>st->mode->maxLM)
-      return OPUS_BAD_ARG;
-   M=1<<LM;
-   N = M*st->mode->shortMdctSize;
-
-   prefilter_mem = st->in_mem+CC*(st->overlap);
-   oldBandE = (opus_val16*)(st->in_mem+CC*(st->overlap+COMBFILTER_MAXPERIOD));
-   oldLogE = oldBandE + CC*st->mode->nbEBands;
-   oldLogE2 = oldLogE + CC*st->mode->nbEBands;
-
-   if (enc==NULL)
-   {
-      tell=1;
-      nbFilledBytes=0;
-   } else {
-      tell=ec_tell(enc);
-      nbFilledBytes=(tell+4)>>3;
-   }
-
-#ifdef CUSTOM_MODES
-   if (st->signalling && enc==NULL)
-   {
-      int tmp = (st->mode->effEBands-st->end)>>1;
-      st->end = IMAX(1, st->mode->effEBands-tmp);
-      compressed[0] = tmp<<5;
-      compressed[0] |= LM<<3;
-      compressed[0] |= (C==2)<<2;
-      /* Convert "standard mode" to Opus header */
-      if (st->mode->Fs==48000 && st->mode->shortMdctSize==120)
-      {
-         int c0 = toOpus(compressed[0]);
-         if (c0<0)
-            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=st->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*st->mode->Fs)/(8*st->mode->Fs)-!!st->signalling));
-      effectiveBytes = nbCompressedBytes;
-   }
-
-   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 = st->end;
-   if (effEnd > st->mode->effEBands)
-      effEnd = st->mode->effEBands;
-
-   ALLOC(in, CC*(N+st->overlap), celt_sig);
-
-   /* Find pitch period and gain */
-   {
-      VARDECL(celt_sig, _pre);
-      celt_sig *pre[2];
-      SAVE_STACK;
-      ALLOC(_pre, CC*(N+COMBFILTER_MAXPERIOD), celt_sig);
-
-      pre[0] = _pre;
-      pre[1] = _pre + (N+COMBFILTER_MAXPERIOD);
-
-      silence = 1;
-      c=0; do {
-         int count = 0;
-         const opus_val16 * OPUS_RESTRICT pcmp = pcm+c;
-         celt_sig * OPUS_RESTRICT inp = in+c*(N+st->overlap)+st->overlap;
-
-         for (i=0;i<N;i++)
-         {
-            celt_sig x, tmp;
-
-            x = SCALEIN(*pcmp);
-#ifndef FIXED_POINT
-            if (!(x==x))
-               x = 0;
-            if (st->clip)
-               x = MAX32(-65536.f, MIN32(65536.f,x));
-#endif
-            if (++count==st->upsample)
-            {
-               count=0;
-               pcmp+=CC;
-            } else {
-               x = 0;
-            }
-            /* Apply pre-emphasis */
-            tmp = MULT16_16(st->mode->preemph[2], x);
-            *inp = tmp + st->preemph_memE[c];
-            st->preemph_memE[c] = MULT16_32_Q15(st->mode->preemph[1], *inp)
-                                   - MULT16_32_Q15(st->mode->preemph[0], tmp);
-            silence = silence && *inp == 0;
-            inp++;
-         }
-         OPUS_COPY(pre[c], prefilter_mem+c*COMBFILTER_MAXPERIOD, COMBFILTER_MAXPERIOD);
-         OPUS_COPY(pre[c]+COMBFILTER_MAXPERIOD, in+c*(N+st->overlap)+st->overlap, N);
-      } while (++c<CC);
-
-#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);
-      }
-      if (nbAvailableBytes>12*C && st->start==0 && !silence && !st->disable_pf && st->complexity >= 5)
-      {
-         VARDECL(opus_val16, pitch_buf);
-         ALLOC(pitch_buf, (COMBFILTER_MAXPERIOD+N)>>1, opus_val16);
-
-         pitch_downsample(pre, pitch_buf, COMBFILTER_MAXPERIOD+N, CC);
-         pitch_search(pitch_buf+(COMBFILTER_MAXPERIOD>>1), pitch_buf, N,
-               COMBFILTER_MAXPERIOD-COMBFILTER_MINPERIOD, &pitch_index);
-         pitch_index = COMBFILTER_MAXPERIOD-pitch_index;
-
-         gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD,
-               N, &pitch_index, st->prefilter_period, st->prefilter_gain);
-         if (pitch_index > COMBFILTER_MAXPERIOD-2)
-            pitch_index = COMBFILTER_MAXPERIOD-2;
-         gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1);
-         if (st->loss_rate>2)
-            gain1 = HALF32(gain1);
-         if (st->loss_rate>4)
-            gain1 = HALF32(gain1);
-         if (st->loss_rate>8)
-            gain1 = 0;
-         prefilter_tapset = st->tapset_decision;
-      } else {
-         gain1 = 0;
-      }
-
-      /* 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)
-      {
-         if(st->start==0 && tell+16<=total_bits)
-            ec_enc_bit_logp(enc, 0, 1);
-         gain1 = 0;
-         pf_on = 0;
-      } else {
-         /*This block is not gated by a total bits check only because
-           of the nbAvailableBytes check above.*/
-         int qg;
-         int octave;
-
-         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));
-         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);
-         if (ec_tell(enc)+2<=total_bits)
-            ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2);
-         else
-           prefilter_tapset = 0;
-         gain1 = QCONST16(0.09375f,15)*(qg+1);
-         pf_on = 1;
-      }
-      /*printf("%d %f\n", pitch_index, gain1);*/
-
-      c=0; do {
-         int offset = st->mode->shortMdctSize-st->mode->overlap;
-         st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
-         OPUS_COPY(in+c*(N+st->overlap), st->in_mem+c*(st->overlap), st->overlap);
-         if (offset)
-            comb_filter(in+c*(N+st->overlap)+st->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);
-
-         comb_filter(in+c*(N+st->overlap)+st->overlap+offset, pre[c]+COMBFILTER_MAXPERIOD+offset,
-               st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1,
-               st->prefilter_tapset, prefilter_tapset, st->mode->window, st->mode->overlap);
-         OPUS_COPY(st->in_mem+c*(st->overlap), in+c*(N+st->overlap)+N, st->overlap);
-
-         if (N>COMBFILTER_MAXPERIOD)
-         {
-            OPUS_MOVE(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_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD+COMBFILTER_MAXPERIOD-N, pre[c]+COMBFILTER_MAXPERIOD, N);
-         }
-      } while (++c<CC);
-
-      RESTORE_STACK;
-   }
-
-   isTransient = 0;
-   shortBlocks = 0;
-   if (LM>0 && ec_tell(enc)+3<=total_bits)
-   {
-      if (st->complexity > 1)
-      {
-         isTransient = transient_analysis(in, N+st->overlap, CC,
-                  st->overlap);
-         if (isTransient)
-            shortBlocks = M;
-      }
-      ec_enc_bit_logp(enc, isTransient, 3);
-   }
-
-   ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */
-   ALLOC(bandE,st->mode->nbEBands*CC, celt_ener);
-   ALLOC(bandLogE,st->mode->nbEBands*CC, opus_val16);
-   /* Compute MDCTs */
-   compute_mdcts(st->mode, shortBlocks, in, freq, CC, LM);
-
-   if (CC==2&&C==1)
-   {
-      for (i=0;i<N;i++)
-         freq[i] = ADD32(HALF32(freq[i]), HALF32(freq[N+i]));
-   }
-   if (st->upsample != 1)
-   {
-      c=0; do
-      {
-         int bound = N/st->upsample;
-         for (i=0;i<bound;i++)
-            freq[c*N+i] *= st->upsample;
-         for (;i<N;i++)
-            freq[c*N+i] = 0;
-      } while (++c<C);
-   }
-   ALLOC(X, C*N, celt_norm);         /**< Interleaved normalised MDCTs */
-
-   compute_band_energies(st->mode, freq, bandE, effEnd, C, M);
-
-   amp2Log2(st->mode, effEnd, st->end, bandE, bandLogE, C);
-
-   /* Band normalisation */
-   normalise_bands(st->mode, freq, X, bandE, effEnd, C, M);
-
-   ALLOC(tf_res, st->mode->nbEBands, int);
-   tf_select = tf_analysis(st->mode, effEnd, C, isTransient, tf_res, effectiveBytes, X, N, LM, st->start, &tf_sum);
-   for (i=effEnd;i<st->end;i++)
-      tf_res[i] = tf_res[effEnd-1];
-
-   ALLOC(error, C*st->mode->nbEBands, opus_val16);
-   quant_coarse_energy(st->mode, st->start, st->end, effEnd, bandLogE,
-         oldBandE, total_bits, error, enc,
-         C, LM, nbAvailableBytes, st->force_intra,
-         &st->delayedIntra, st->complexity >= 4, st->loss_rate);
-
-   tf_encode(st->start, st->end, isTransient, tf_res, LM, tf_select, enc);
-
-   if (ec_tell(enc)+4<=total_bits)
-   {
-      if (shortBlocks || st->complexity < 3 
-          || nbAvailableBytes < 10*C || st->start!=0)
-      {
-         if (st->complexity == 0)
-            st->spread_decision = SPREAD_NONE;
-         else
-            st->spread_decision = SPREAD_NORMAL;
-      } else {
-         st->spread_decision = spreading_decision(st->mode, X,
-               &st->tonal_average, st->spread_decision, &st->hf_average,
-               &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M);
-      }
-      ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5);
-   }
-
-   ALLOC(cap, st->mode->nbEBands, int);
-   ALLOC(offsets, st->mode->nbEBands, int);
-
-   init_caps(st->mode,cap,LM,C);
-   for (i=0;i<st->mode->nbEBands;i++)
-      offsets[i] = 0;
-   /* Dynamic allocation code */
-   /* Make sure that dynamic allocation can't make us bust the budget */
-   if (effectiveBytes > 50 && LM>=1)
-   {
-      int t1, t2;
-      if (LM <= 1)
-      {
-         t1 = 3;
-         t2 = 5;
-      } else {
-         t1 = 2;
-         t2 = 4;
-      }
-      for (i=st->start+1;i<st->end-1;i++)
-      {
-         opus_val32 d2;
-         d2 = 2*bandLogE[i]-bandLogE[i-1]-bandLogE[i+1];
-         if (C==2)
-            d2 = HALF32(d2 + 2*bandLogE[i+st->mode->nbEBands]-
-                  bandLogE[i-1+st->mode->nbEBands]-bandLogE[i+1+st->mode->nbEBands]);
-#ifdef FUZZING
-         if((rand()&0xF)==0)
-         {
-            offsets[i] += 1;
-            if((rand()&0x3)==0)
-               offsets[i] += 1+(rand()&0x3);
-         }
-#else
-         if (d2 > SHL16(t1,DB_SHIFT))
-            offsets[i] += 1;
-         if (d2 > SHL16(t2,DB_SHIFT))
-            offsets[i] += 1;
-#endif
-      }
-   }
-   dynalloc_logp = 6;
-   total_bits<<=BITRES;
-   total_boost = 0;
-   tell = ec_tell_frac(enc);
-   for (i=st->start;i<st->end;i++)
-   {
-      int width, quanta;
-      int dynalloc_loop_logp;
-      int boost;
-      int j;
-      width = C*(st->mode->eBands[i+1]-st->mode->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;
-   }
-   alloc_trim = 5;
-   if (tell+(6<<BITRES) <= total_bits - total_boost)
-   {
-      alloc_trim = alloc_trim_analysis(st->mode, X, bandLogE,
-            st->end, LM, C, N);
-      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;
-     opus_int32 min_allowed;
-     int lm_diff = st->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));
-     target = vbr_rate + (st->vbr_offset>>lm_diff) - ((40*C+20)<<BITRES);
-
-     /* Shortblocks get a large boost in bitrate, but since they
-        are uncommon long blocks are not greatly affected */
-     if (shortBlocks || tf_sum < -2*(st->end-st->start))
-        target = 7*target/4;
-     else if (tf_sum < -(st->end-st->start))
-        target = 3*target/2;
-     else if (M > 1)
-        target-=(target+14)/28;
-
-     /* 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 - nbFilledBytes;
-
-     nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
-     nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
-     nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes) - nbFilledBytes;
-
-     /* 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 */
-     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+nbFilledBytes);
-     /* This moves the raw bits to take into account the new compressed size */
-     ec_enc_shrink(enc, nbCompressedBytes);
-   }
-   if (C==2)
-   {
-      int effectiveRate;
-
-      /* Always use MS for 2.5 ms frames until we can do a better analysis */
-      if (LM!=0)
-         dual_stereo = stereo_analysis(st->mode, X, LM, N);
-
-      /* Account for coarse energy */
-      effectiveRate = (8*effectiveBytes - 80)>>LM;
-
-      /* effectiveRate in kb/s */
-      effectiveRate = 2*effectiveRate/5;
-      if (effectiveRate<35)
-         intensity = 8;
-      else if (effectiveRate<50)
-         intensity = 12;
-      else if (effectiveRate<68)
-         intensity = 16;
-      else if (effectiveRate<84)
-         intensity = 18;
-      else if (effectiveRate<102)
-         intensity = 19;
-      else if (effectiveRate<130)
-         intensity = 20;
-      else
-         intensity = 100;
-      intensity = IMIN(st->end,IMAX(st->start, intensity));
-   }
-
-   /* Bit allocation */
-   ALLOC(fine_quant, st->mode->nbEBands, int);
-   ALLOC(pulses, st->mode->nbEBands, int);
-   ALLOC(fine_priority, st->mode->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;
-   codedBands = compute_allocation(st->mode, st->start, st->end, offsets, cap,
-         alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
-         fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands);
-   st->lastCodedBands = codedBands;
-
-   quant_fine_energy(st->mode, st->start, st->end, oldBandE, error, fine_quant, enc, C);
-
-#ifdef MEASURE_NORM_MSE
-   float X0[3000];
-   float bandE0[60];
-   c=0; do
-      for (i=0;i<N;i++)
-         X0[i+c*N] = X[i+c*N];
-   while (++c<C);
-   for (i=0;i<C*st->mode->nbEBands;i++)
-      bandE0[i] = bandE[i];
-#endif
-
-   /* Residual quantisation */
-   ALLOC(collapse_masks, C*st->mode->nbEBands, unsigned char);
-   quant_all_bands(1, st->mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks,
-         bandE, pulses, shortBlocks, st->spread_decision, dual_stereo, intensity, tf_res,
-         nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv, balance, enc, LM, codedBands, &st->rng);
-
-   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(st->mode, st->start, st->end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
-
-   if (silence)
-   {
-      for (i=0;i<C*st->mode->nbEBands;i++)
-         oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
-   }
-
-#ifdef RESYNTH
-   /* Re-synthesis of the coded audio if required */
-   {
-      celt_sig *out_mem[2];
-      celt_sig *overlap_mem[2];
-
-      log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
-      if (silence)
-      {
-         for (i=0;i<C*st->mode->nbEBands;i++)
-            bandE[i] = 0;
-      }
-
-#ifdef MEASURE_NORM_MSE
-      measure_norm_mse(st->mode, X, X0, bandE, bandE0, M, N, C);
-#endif
-      if (anti_collapse_on)
-      {
-         anti_collapse(st->mode, X, collapse_masks, LM, C, N,
-               st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
-      }
-
-      /* Synthesis */
-      denormalise_bands(st->mode, X, freq, bandE, effEnd, C, M);
-
-      OPUS_MOVE(st->syn_mem[0], st->syn_mem[0]+N, MAX_PERIOD);
-      if (CC==2)
-         OPUS_MOVE(st->syn_mem[1], st->syn_mem[1]+N, MAX_PERIOD);
-
-      c=0; do
-         for (i=0;i<M*st->mode->eBands[st->start];i++)
-            freq[c*N+i] = 0;
-      while (++c<C);
-      c=0; do
-         for (i=M*st->mode->eBands[st->end];i<N;i++)
-            freq[c*N+i] = 0;
-      while (++c<C);
-
-      if (CC==2&&C==1)
-      {
-         for (i=0;i<N;i++)
-            freq[N+i] = freq[i];
-      }
-
-      out_mem[0] = st->syn_mem[0]+MAX_PERIOD;
-      if (CC==2)
-         out_mem[1] = st->syn_mem[1]+MAX_PERIOD;
-
-      overlap_mem[0] = (celt_sig*)(oldLogE2 + CC*st->mode->nbEBands);
-      if (CC==2)
-         overlap_mem[1] = overlap_mem[0] + st->overlap;
-
-      compute_inv_mdcts(st->mode, shortBlocks, freq, out_mem, overlap_mem, CC, LM);
-
-      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, st->mode->shortMdctSize,
-               st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset,
-               st->mode->window, st->overlap);
-         if (LM!=0)
-            comb_filter(out_mem[c]+st->mode->shortMdctSize, out_mem[c]+st->mode->shortMdctSize, st->prefilter_period, pitch_index, N-st->mode->shortMdctSize,
-                  st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset,
-                  st->mode->window, st->mode->overlap);
-      } while (++c<CC);
-
-      deemphasis(out_mem, (opus_val16*)pcm, N, CC, st->upsample, st->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) {
-      for (i=0;i<st->mode->nbEBands;i++)
-         oldBandE[st->mode->nbEBands+i]=oldBandE[i];
-   }
-
-   if (!isTransient)
-   {
-      for (i=0;i<CC*st->mode->nbEBands;i++)
-         oldLogE2[i] = oldLogE[i];
-      for (i=0;i<CC*st->mode->nbEBands;i++)
-         oldLogE[i] = oldBandE[i];
-   } else {
-      for (i=0;i<CC*st->mode->nbEBands;i++)
-         oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
-   }
-   /* In case start or end were to change */
-   c=0; do
-   {
-      for (i=0;i<st->start;i++)
-      {
-         oldBandE[c*st->mode->nbEBands+i]=0;
-         oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
-      }
-      for (i=st->end;i<st->mode->nbEBands;i++)
-      {
-         oldBandE[c*st->mode->nbEBands+i]=0;
-         oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
-      }
-   } while (++c<CC);
-
-   if (isTransient)
-      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_RESET_STATE:
-      {
-         int i;
-         opus_val16 *oldBandE, *oldLogE, *oldLogE2;
-         oldBandE = (opus_val16*)(st->in_mem+st->channels*(st->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_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;
-      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;
-}
-
-/**********************************************************************/
-/*                                                                    */
-/*                             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;
-
-   /* 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 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;
-
-   st->loss_count = 0;
-
-   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 */
-
-static void celt_decode_lost(CELTDecoder * OPUS_RESTRICT st, opus_val16 * OPUS_RESTRICT pcm, int N, int LM)
-{
-   int c;
-   int pitch_index;
-   opus_val16 fade = Q15ONE;
-   int i, len;
-   const int C = st->channels;
-   int offset;
-   celt_sig *out_mem[2];
-   celt_sig *decode_mem[2];
-   celt_sig *overlap_mem[2];
-   opus_val16 *lpc;
-   opus_val32 *out_syn[2];
-   opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
-   const OpusCustomMode *mode;
-   int nbEBands;
-   int overlap;
-   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+st->overlap);
-      out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
-      overlap_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE;
-   } while (++c<C);
-   lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*C);
-   oldBandE = lpc+C*LPC_ORDER;
-   oldLogE = oldBandE + 2*nbEBands;
-   oldLogE2 = oldLogE + 2*nbEBands;
-   backgroundLogE = oldLogE2  + 2*nbEBands;
-
-   c=0; do {
-      out_syn[c] = out_mem[c]+MAX_PERIOD-N;
-   } while (++c<C);
-
-   len = N+overlap;
-
-   if (st->loss_count >= 5 || st->start!=0)
-   {
-      /* Noise-based PLC/CNG */
-      VARDECL(celt_sig, freq);
-      VARDECL(celt_norm, X);
-      VARDECL(celt_ener, bandE);
-      opus_uint32 seed;
-      int effEnd;
-
-      effEnd = st->end;
-      if (effEnd > mode->effEBands)
-         effEnd = mode->effEBands;
-
-      ALLOC(freq, C*N, celt_sig); /**< Interleaved signal MDCTs */
-      ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
-      ALLOC(bandE, nbEBands*C, celt_ener);
-
-      if (st->loss_count >= 5)
-         log2Amp(mode, st->start, st->end, bandE, backgroundLogE, C);
-      else {
-         /* Energy decay */
-         opus_val16 decay = st->loss_count==0 ? QCONST16(1.5f, DB_SHIFT) : QCONST16(.5f, DB_SHIFT);
-         c=0; do
-         {
-            for (i=st->start;i<st->end;i++)
-               oldBandE[c*nbEBands+i] -= decay;
-         } while (++c<C);
-         log2Amp(mode, st->start, st->end, bandE, oldBandE, C);
-      }
-      seed = st->rng;
-      for (c=0;c<C;c++)
-      {
-         for (i=0;i<(st->mode->eBands[st->start]<<LM);i++)
-            X[c*N+i] = 0;
-         for (i=st->start;i<mode->effEBands;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);
-         }
-         for (i=(st->mode->eBands[st->end]<<LM);i<N;i++)
-            X[c*N+i] = 0;
-      }
-      st->rng = seed;
-
-      denormalise_bands(mode, X, freq, bandE, mode->effEBands, C, 1<<LM);
-
-      c=0; do
-         for (i=0;i<st->mode->eBands[st->start]<<LM;i++)
-            freq[c*N+i] = 0;
-      while (++c<C);
-      c=0; do {
-         int bound = eBands[effEnd]<<LM;
-         if (st->downsample!=1)
-            bound = IMIN(bound, N/st->downsample);
-         for (i=bound;i<N;i++)
-            freq[c*N+i] = 0;
-      } while (++c<C);
-      c=0; do {
-         OPUS_MOVE(decode_mem[c], decode_mem[c]+N, DECODE_BUFFER_SIZE-N+overlap);
-      } while (++c<C);
-      compute_inv_mdcts(mode, 0, freq, out_syn, overlap_mem, C, LM);
-   } else {
-      /* Pitch-based PLC */
-      VARDECL(opus_val32, etmp);
-
-      if (st->loss_count == 0)
-      {
-         opus_val16 pitch_buf[DECODE_BUFFER_SIZE>>1];
-         /* Corresponds to a min pitch of 67 Hz. It's possible to save CPU in this
-         search by using only part of the decode buffer */
-         int poffset = 720;
-         pitch_downsample(decode_mem, pitch_buf, DECODE_BUFFER_SIZE, C);
-         /* Max pitch is 100 samples (480 Hz) */
-         pitch_search(pitch_buf+((poffset)>>1), pitch_buf, DECODE_BUFFER_SIZE-poffset,
-               poffset-100, &pitch_index);
-         pitch_index = poffset-pitch_index;
-         st->last_pitch_index = pitch_index;
-      } else {
-         pitch_index = st->last_pitch_index;
-         fade = QCONST16(.8f,15);
-      }
-
-      ALLOC(etmp, overlap, opus_val32);
-      c=0; do {
-         opus_val16 exc[MAX_PERIOD];
-         opus_val32 ac[LPC_ORDER+1];
-         opus_val16 decay;
-         opus_val16 attenuation;
-         opus_val32 S1=0;
-         opus_val16 mem[LPC_ORDER]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
-         opus_val32 *e = out_syn[c];
-
-
-         offset = MAX_PERIOD-pitch_index;
-         for (i=0;i<MAX_PERIOD;i++)
-            exc[i] = ROUND16(out_mem[c][i], SIG_SHIFT);
-
-         /* Compute LPC coefficients for the last MAX_PERIOD samples before the loss so we can
-            work in the excitation-filter domain */
-         if (st->loss_count == 0)
-         {
-            _celt_autocorr(exc, ac, mode->window, overlap,
-                  LPC_ORDER, MAX_PERIOD);
-
-            /* 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<=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]*(.008f*i)*(.008f*i);
-#endif
-            }
-
-            _celt_lpc(lpc+c*LPC_ORDER, ac, LPC_ORDER);
-         }
-         /* Samples just before the beginning of exc  */
-         for (i=0;i<LPC_ORDER;i++)
-            mem[i] = ROUND16(out_mem[c][-1-i], SIG_SHIFT);
-         /* Compute the excitation for MAX_PERIOD samples before the loss */
-         celt_fir(exc, lpc+c*LPC_ORDER, exc, MAX_PERIOD, LPC_ORDER, mem);
-
-         /* 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 period;
-            if (pitch_index <= MAX_PERIOD/2)
-               period = pitch_index;
-            else
-               period = MAX_PERIOD/2;
-            for (i=0;i<period;i++)
-            {
-               E1 += SHR32(MULT16_16(exc[MAX_PERIOD-period+i],exc[MAX_PERIOD-period+i]),8);
-               E2 += SHR32(MULT16_16(exc[MAX_PERIOD-2*period+i],exc[MAX_PERIOD-2*period+i]),8);
-            }
-            if (E1 > E2)
-               E1 = E2;
-            decay = celt_sqrt(frac_div32(SHR32(E1,1),E2));
-            attenuation = decay;
-         }
-
-         /* Move memory one frame to the left */
-         OPUS_MOVE(decode_mem[c], decode_mem[c]+N, DECODE_BUFFER_SIZE-N+overlap);
-
-         /* Extrapolate excitation with the right period, taking decay into account */
-         for (i=0;i<len;i++)
-         {
-            opus_val16 tmp;
-            if (offset+i >= MAX_PERIOD)
-            {
-               offset -= pitch_index;
-               attenuation = MULT16_16_Q15(attenuation, decay);
-            }
-            e[i] = SHL32(EXTEND32(MULT16_16_Q15(attenuation, exc[offset+i])), SIG_SHIFT);
-            /* Compute the energy of the previously decoded signal whose
-               excitation we're copying */
-            tmp = ROUND16(out_mem[c][-N+offset+i],SIG_SHIFT);
-            S1 += SHR32(MULT16_16(tmp,tmp),8);
-         }
-
-         /* 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++)
-            mem[i] = ROUND16(out_mem[c][MAX_PERIOD-N-1-i], SIG_SHIFT);
-         /* Apply the fading if not the first loss */
-         for (i=0;i<len;i++)
-            e[i] = MULT16_32_Q15(fade, e[i]);
-         /* Synthesis filter -- back in the signal domain */
-         celt_iir(e, lpc+c*LPC_ORDER, e, len, LPC_ORDER, mem);
-
-         /* 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<len;i++)
-            {
-               opus_val16 tmp = ROUND16(e[i],SIG_SHIFT);
-               S2 += SHR32(MULT16_16(tmp,tmp),8);
-            }
-            /* This checks for an "explosion" in the synthesis */
-#ifdef FIXED_POINT
-            if (!(S1 > SHR32(S2,2)))
-#else
-            /* Float test is written this way to catch NaNs at the same time */
-            if (!(S1 > 0.2f*S2))
-#endif
-            {
-               for (i=0;i<len;i++)
-                  e[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(mode->window[i], Q15ONE-ratio);
-                  e[i] = MULT16_32_Q15(tmp_g, e[i]);
-               }
-               for (i=overlap;i<len;i++)
-                  e[i] = MULT16_32_Q15(ratio, e[i]);
-            }
-         }
-
-         /* Apply 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, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
-               -st->postfilter_gain, -st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
-               NULL, 0);
-
-         /* Simulate TDAC on the concealed audio so that it blends with the
-            MDCT of next frames. */
-         for (i=0;i<overlap/2;i++)
-         {
-            opus_val32 tmp;
-            tmp = MULT16_32_Q15(mode->window[i],           etmp[overlap-1-i]) +
-                  MULT16_32_Q15(mode->window[overlap-i-1], etmp[i          ]);
-            out_mem[c][MAX_PERIOD+i] = MULT16_32_Q15(mode->window[overlap-i-1], tmp);
-            out_mem[c][MAX_PERIOD+overlap-i-1] = MULT16_32_Q15(mode->window[i], tmp);
-         }
-      } while (++c<C);
-   }
-
-   deemphasis(out_syn, pcm, N, C, st->downsample, mode->preemph, st->preemph_memD);
-
-   st->loss_count++;
-
-   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 c, i, N;
-   int spread_decision;
-   opus_int32 bits;
-   ec_dec _dec;
-   VARDECL(celt_sig, freq);
-   VARDECL(celt_norm, X);
-   VARDECL(celt_ener, bandE);
-   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 *out_mem[2];
-   celt_sig *decode_mem[2];
-   celt_sig *overlap_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 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;
-   ALLOC_STACK;
-
-   frame_size *= st->downsample;
-
-   c=0; do {
-      decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+st->overlap);
-      out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
-      overlap_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE;
-   } while (++c<CC);
-   lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*CC);
-   oldBandE = lpc+CC*LPC_ORDER;
-   oldLogE = oldBandE + 2*st->mode->nbEBands;
-   oldLogE2 = oldLogE + 2*st->mode->nbEBands;
-   backgroundLogE = oldLogE2  + 2*st->mode->nbEBands;
-
-#ifdef CUSTOM_MODES
-   if (st->signalling && data!=NULL)
-   {
-      int data0=data[0];
-      /* Convert "standard mode" to Opus header */
-      if (st->mode->Fs==48000 && st->mode->shortMdctSize==120)
-      {
-         data0 = fromOpus(data0);
-         if (data0<0)
-            return OPUS_INVALID_PACKET;
-      }
-      st->end = IMAX(1, st->mode->effEBands-2*(data0>>5));
-      LM = (data0>>3)&0x3;
-      C = 1 + ((data0>>2)&0x1);
-      data++;
-      len--;
-      if (LM>st->mode->maxLM)
-         return OPUS_INVALID_PACKET;
-      if (frame_size < st->mode->shortMdctSize<<LM)
-         return OPUS_BUFFER_TOO_SMALL;
-      else
-         frame_size = st->mode->shortMdctSize<<LM;
-   } else {
-#else
-   {
-#endif
-      for (LM=0;LM<=st->mode->maxLM;LM++)
-         if (st->mode->shortMdctSize<<LM==frame_size)
-            break;
-      if (LM>st->mode->maxLM)
-         return OPUS_BAD_ARG;
-   }
-   M=1<<LM;
-
-   if (len<0 || len>1275 || pcm==NULL)
-      return OPUS_BAD_ARG;
-
-   N = M*st->mode->shortMdctSize;
-
-   effEnd = st->end;
-   if (effEnd > st->mode->effEBands)
-      effEnd = st->mode->effEBands;
-
-   if (data == NULL || len<=1)
-   {
-      celt_decode_lost(st, pcm, N, LM);
-      RESTORE_STACK;
-      return frame_size/st->downsample;
-   }
-
-   ALLOC(freq, IMAX(CC,C)*N, celt_sig); /**< Interleaved signal MDCTs */
-   ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
-   ALLOC(bandE, st->mode->nbEBands*C, celt_ener);
-   c=0; do
-      for (i=0;i<M*st->mode->eBands[st->start];i++)
-         X[c*N+i] = 0;
-   while (++c<C);
-   c=0; do
-      for (i=M*st->mode->eBands[effEnd];i<N;i++)
-         X[c*N+i] = 0;
-   while (++c<C);
-
-   if (dec == NULL)
-   {
-      ec_dec_init(&_dec,(unsigned char*)data,len);
-      dec = &_dec;
-   }
-
-   if (C==1)
-   {
-      for (i=0;i<st->mode->nbEBands;i++)
-         oldBandE[i]=MAX16(oldBandE[i],oldBandE[st->mode->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 (st->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(st->mode, st->start, st->end, oldBandE,
-         intra_ener, dec, C, LM);
-
-   ALLOC(tf_res, st->mode->nbEBands, int);
-   tf_decode(st->start, st->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(pulses, st->mode->nbEBands, int);
-   ALLOC(cap, st->mode->nbEBands, int);
-   ALLOC(offsets, st->mode->nbEBands, int);
-   ALLOC(fine_priority, st->mode->nbEBands, int);
-
-   init_caps(st->mode,cap,LM,C);
-
-   dynalloc_logp = 6;
-   total_bits<<=BITRES;
-   tell = ec_tell_frac(dec);
-   for (i=st->start;i<st->end;i++)
-   {
-      int width, quanta;
-      int dynalloc_loop_logp;
-      int boost;
-      width = C*(st->mode->eBands[i+1]-st->mode->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, st->mode->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;
-   codedBands = compute_allocation(st->mode, st->start, st->end, offsets, cap,
-         alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
-         fine_quant, fine_priority, C, LM, dec, 0, 0);
-
-   unquant_fine_energy(st->mode, st->start, st->end, oldBandE, fine_quant, dec, C);
-
-   /* Decode fixed codebook */
-   ALLOC(collapse_masks, C*st->mode->nbEBands, unsigned char);
-   quant_all_bands(0, st->mode, st->start, st->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);
-
-   if (anti_collapse_rsv > 0)
-   {
-      anti_collapse_on = ec_dec_bits(dec, 1);
-   }
-
-   unquant_energy_finalise(st->mode, st->start, st->end, oldBandE,
-         fine_quant, fine_priority, len*8-ec_tell(dec), dec, C);
-
-   if (anti_collapse_on)
-      anti_collapse(st->mode, X, collapse_masks, LM, C, N,
-            st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
-
-   log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
-
-   if (silence)
-   {
-      for (i=0;i<C*st->mode->nbEBands;i++)
-      {
-         bandE[i] = 0;
-         oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
-      }
-   }
-   /* Synthesis */
-   denormalise_bands(st->mode, X, freq, bandE, effEnd, C, M);
-
-   OPUS_MOVE(decode_mem[0], decode_mem[0]+N, DECODE_BUFFER_SIZE-N);
-   if (CC==2)
-      OPUS_MOVE(decode_mem[1], decode_mem[1]+N, DECODE_BUFFER_SIZE-N);
-
-   c=0; do
-      for (i=0;i<M*st->mode->eBands[st->start];i++)
-         freq[c*N+i] = 0;
-   while (++c<C);
-   c=0; do {
-      int bound = M*st->mode->eBands[effEnd];
-      if (st->downsample!=1)
-         bound = IMIN(bound, N/st->downsample);
-      for (i=bound;i<N;i++)
-         freq[c*N+i] = 0;
-   } while (++c<C);
-
-   out_syn[0] = out_mem[0]+MAX_PERIOD-N;
-   if (CC==2)
-      out_syn[1] = out_mem[1]+MAX_PERIOD-N;
-
-   if (CC==2&&C==1)
-   {
-      for (i=0;i<N;i++)
-         freq[N+i] = freq[i];
-   }
-   if (CC==1&&C==2)
-   {
-      for (i=0;i<N;i++)
-         freq[i] = HALF32(ADD32(freq[i],freq[N+i]));
-   }
-
-   /* Compute inverse MDCTs */
-   compute_inv_mdcts(st->mode, shortBlocks, freq, out_syn, overlap_mem, CC, LM);
-
-   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, st->mode->shortMdctSize,
-            st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
-            st->mode->window, st->overlap);
-      if (LM!=0)
-         comb_filter(out_syn[c]+st->mode->shortMdctSize, out_syn[c]+st->mode->shortMdctSize, st->postfilter_period, postfilter_pitch, N-st->mode->shortMdctSize,
-               st->postfilter_gain, postfilter_gain, st->postfilter_tapset, postfilter_tapset,
-               st->mode->window, st->mode->overlap);
-
-   } 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) {
-      for (i=0;i<st->mode->nbEBands;i++)
-         oldBandE[st->mode->nbEBands+i]=oldBandE[i];
-   }
-
-   /* In case start or end were to change */
-   if (!isTransient)
-   {
-      for (i=0;i<2*st->mode->nbEBands;i++)
-         oldLogE2[i] = oldLogE[i];
-      for (i=0;i<2*st->mode->nbEBands;i++)
-         oldLogE[i] = oldBandE[i];
-      for (i=0;i<2*st->mode->nbEBands;i++)
-         backgroundLogE[i] = MIN16(backgroundLogE[i] + M*QCONST16(0.001f,DB_SHIFT), oldBandE[i]);
-   } else {
-      for (i=0;i<2*st->mode->nbEBands;i++)
-         oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
-   }
-   c=0; do
-   {
-      for (i=0;i<st->start;i++)
-      {
-         oldBandE[c*st->mode->nbEBands+i]=0;
-         oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
-      }
-      for (i=st->end;i<st->mode->nbEBands;i++)
-      {
-         oldBandE[c*st->mode->nbEBands+i]=0;
-         oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
-      }
-   } while (++c<2);
-   st->rng = dec->rng;
-
-   deemphasis(out_syn, pcm, N, CC, st->downsample, st->mode->preemph, st->preemph_memD);
-   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);
-}
-
-#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);
-   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);
-}
-
-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);
-
-   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);
-      }
-      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;
-      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;
-}
-
 
 
 const char *opus_strerror(int error)
@@ -2895,7 +212,7 @@
 
 const char *opus_get_version_string(void)
 {
-    return "libopus " OPUS_VERSION
+    return "libopus " PACKAGE_VERSION
 #ifdef FIXED_POINT
           "-fixed"
 #endif
diff --git a/celt/celt.h b/celt/celt.h
index 218cd88..cdb76c8 100644
--- a/celt/celt.h
+++ b/celt/celt.h
@@ -50,7 +50,19 @@
 #define CELTDecoder OpusCustomDecoder
 #define CELTMode OpusCustomMode
 
-#define _celt_check_mode_ptr_ptr(ptr) ((ptr) + ((ptr) - (const CELTMode**)(ptr)))
+typedef struct {
+   int valid;
+   float tonality;
+   float tonality_slope;
+   float noisiness;
+   float activity;
+   float music_prob;
+   int        bandwidth;
+}AnalysisInfo;
+
+#define __celt_check_mode_ptr_ptr(ptr) ((ptr) + ((ptr) - (const CELTMode**)(ptr)))
+
+#define __celt_check_analysis_ptr(ptr) ((ptr) + ((ptr) - (const AnalysisInfo*)(ptr)))
 
 /* Encoder/decoder Requests */
 
@@ -81,12 +93,24 @@
 
 #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_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)
 
 /* Encoder stuff */
 
@@ -110,6 +134,78 @@
 #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 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 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 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 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);
+
+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, celt_sig * OPUS_RESTRICT scratch);
+
+void compute_inv_mdcts(const CELTMode *mode, int shortBlocks, celt_sig *X,
+      celt_sig * OPUS_RESTRICT out_mem[], int C, int LM);
+#endif
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/celt/celt_decoder.c b/celt/celt_decoder.c
new file mode 100644
index 0000000..4424b97
--- /dev/null
+++ b/celt/celt_decoder.c
@@ -0,0 +1,1195 @@
+/* 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"
+
+/**********************************************************************/
+/*                                                                    */
+/*                             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 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 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;
+   st->arch = opus_select_arch();
+
+   st->loss_count = 0;
+
+   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 */
+
+static inline opus_val16 SIG2WORD16(celt_sig x)
+{
+#ifdef FIXED_POINT
+   x = PSHR32(x, SIG_SHIFT);
+   x = MAX32(x, -32768);
+   x = MIN32(x, 32767);
+   return EXTRACT16(x);
+#else
+   return (opus_val16)x;
+#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, celt_sig * OPUS_RESTRICT scratch)
+{
+   int c;
+   int Nd;
+   int apply_downsampling=0;
+   opus_val16 coef0;
+
+   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;
+            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] + m;
+            m = MULT16_32_Q15(coef0, tmp);
+            scratch[j] = tmp;
+         }
+         apply_downsampling=1;
+      } else {
+         /* Shortcut for the standard (non-custom modes) case */
+         for (j=0;j<N;j++)
+         {
+            celt_sig tmp = x[j] + m + VERY_SMALL;
+            m = MULT16_32_Q15(coef0, tmp);
+            y[j*C] = SCALEOUT(SIG2WORD16(tmp));
+         }
+      }
+      mem[c] = m;
+
+      if (apply_downsampling)
+      {
+         /* Perform down-sampling */
+         for (j=0;j<Nd;j++)
+            y[j*C] = SCALEOUT(SIG2WORD16(scratch[j*downsample]));
+      }
+   } while (++c<C);
+}
+
+/** Compute the IMDCT and apply window for all sub-frames and
+    all channels in a frame */
+#ifndef RESYNTH
+static
+#endif
+void compute_inv_mdcts(const CELTMode *mode, int shortBlocks, celt_sig *X,
+      celt_sig * OPUS_RESTRICT out_mem[], int C, int LM)
+{
+   int b, c;
+   int B;
+   int N;
+   int shift;
+   const int overlap = OVERLAP(mode);
+
+   if (shortBlocks)
+   {
+      B = shortBlocks;
+      N = mode->shortMdctSize;
+      shift = mode->maxLM;
+   } else {
+      B = 1;
+      N = mode->shortMdctSize<<LM;
+      shift = mode->maxLM-LM;
+   }
+   c=0; do {
+      /* IMDCT on the interleaved the sub-frames, overlap-add is performed by the IMDCT */
+      for (b=0;b<B;b++)
+         clt_mdct_backward(&mode->mdct, &X[b+c*N*B], out_mem[c]+N*b, mode->window, overlap, shift, B);
+   } while (++c<C);
+}
+
+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 void celt_decode_lost(CELTDecoder * OPUS_RESTRICT st, opus_val16 * OPUS_RESTRICT pcm, 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 downsample;
+   int loss_count;
+   int noise_based;
+   const opus_int16 *eBands;
+   VARDECL(celt_sig, scratch);
+   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;
+   downsample = st->downsample;
+   noise_based = loss_count >= 5 || start != 0;
+   ALLOC(scratch, noise_based?N*C:N, celt_sig);
+   if (noise_based)
+   {
+      /* Noise-based PLC/CNG */
+      celt_sig *freq;
+      VARDECL(celt_norm, X);
+      opus_uint32 seed;
+      opus_val16 *plcLogE;
+      int end;
+      int effEnd;
+
+      end = st->end;
+      effEnd = IMAX(start, IMIN(end, mode->effEBands));
+
+      /* Share the interleaved signal MDCT coefficient buffer with the
+         deemphasis scratch buffer. */
+      freq = scratch;
+      ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
+
+      if (loss_count >= 5)
+         plcLogE = backgroundLogE;
+      else {
+         /* Energy decay */
+         opus_val16 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] -= decay;
+         } while (++c<C);
+         plcLogE = oldBandE;
+      }
+      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->rng = seed;
+
+      denormalise_bands(mode, X, freq, plcLogE, start, effEnd, C, 1<<LM);
+
+      c=0; do {
+         int bound = eBands[effEnd]<<LM;
+         if (downsample!=1)
+            bound = IMIN(bound, N/downsample);
+         for (i=bound;i<N;i++)
+            freq[c*N+i] = 0;
+      } while (++c<C);
+      c=0; do {
+         OPUS_MOVE(decode_mem[c], decode_mem[c]+N,
+               DECODE_BUFFER_SIZE-N+(overlap>>1));
+      } while (++c<C);
+      compute_inv_mdcts(mode, 0, freq, out_syn, C, LM);
+   } else {
+      /* Pitch-based PLC */
+      const opus_val16 *window;
+      opus_val16 fade = Q15ONE;
+      int pitch_index;
+      VARDECL(opus_val32, etmp);
+      VARDECL(opus_val16, exc);
+
+      if (loss_count == 0)
+      {
+         VARDECL( opus_val16, lp_pitch_buf );
+         ALLOC( lp_pitch_buf, DECODE_BUFFER_SIZE>>1, opus_val16 );
+         pitch_downsample(decode_mem, lp_pitch_buf, DECODE_BUFFER_SIZE, C);
+         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);
+         pitch_index = PLC_PITCH_LAG_MAX-pitch_index;
+         st->last_pitch_index = pitch_index;
+      } else {
+         pitch_index = st->last_pitch_index;
+         fade = QCONST16(.8f,15);
+      }
+
+      ALLOC(etmp, overlap, opus_val32);
+      ALLOC(exc, MAX_PERIOD, opus_val16);
+      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);
+            /* 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);
+         }
+         /* 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. */
+         {
+            opus_val16 lpc_mem[LPC_ORDER];
+            for (i=0;i<LPC_ORDER;i++)
+            {
+               lpc_mem[i] =
+                     ROUND16(buf[DECODE_BUFFER_SIZE-exc_length-1-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, lpc_mem);
+         }
+
+         /* 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), 8);
+         }
+
+         {
+            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);
+         }
+
+         /* 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), 8);
+            }
+            /* 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);
+
+         /* 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);
+   }
+
+   deemphasis(out_syn, pcm, N, C, downsample,
+         mode->preemph, st->preemph_memD, scratch);
+
+   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 c, i, N;
+   int spread_decision;
+   opus_int32 bits;
+   ec_dec _dec;
+   VARDECL(celt_sig, freq);
+   VARDECL(celt_norm, X);
+   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 *out_mem[2];
+   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 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;
+   frame_size *= st->downsample;
+
+   c=0; do {
+      decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+overlap);
+      out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
+   } while (++c<CC);
+   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 = 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;
+
+   effEnd = st->end;
+   if (effEnd > mode->effEBands)
+      effEnd = mode->effEBands;
+
+   if (data == NULL || len<=1)
+   {
+      celt_decode_lost(st, pcm, N, LM);
+      RESTORE_STACK;
+      return frame_size/st->downsample;
+   }
+
+   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 (st->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, st->start, st->end, oldBandE,
+         intra_ener, dec, C, LM);
+
+   ALLOC(tf_res, nbEBands, int);
+   tf_decode(st->start, st->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=st->start;i<st->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, st->start, st->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, st->start, st->end, oldBandE, fine_quant, dec, C);
+
+   /* Decode fixed codebook */
+   ALLOC(collapse_masks, C*nbEBands, unsigned char);
+   ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
+
+   quant_all_bands(0, mode, st->start, st->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);
+
+   if (anti_collapse_rsv > 0)
+   {
+      anti_collapse_on = ec_dec_bits(dec, 1);
+   }
+
+   unquant_energy_finalise(mode, st->start, st->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,
+            st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
+
+   ALLOC(freq, IMAX(CC,C)*N, celt_sig); /**< Interleaved signal MDCTs */
+
+   if (silence)
+   {
+      for (i=0;i<C*nbEBands;i++)
+         oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
+      for (i=0;i<C*N;i++)
+         freq[i] = 0;
+   } else {
+      /* Synthesis */
+      denormalise_bands(mode, X, freq, oldBandE, st->start, effEnd, C, M);
+   }
+   c=0; do {
+      OPUS_MOVE(decode_mem[c], decode_mem[c]+N, DECODE_BUFFER_SIZE-N+overlap/2);
+   } while (++c<CC);
+
+   c=0; do {
+      int bound = M*eBands[effEnd];
+      if (st->downsample!=1)
+         bound = IMIN(bound, N/st->downsample);
+      for (i=bound;i<N;i++)
+         freq[c*N+i] = 0;
+   } while (++c<C);
+
+   c=0; do {
+      out_syn[c] = out_mem[c]+MAX_PERIOD-N;
+   } while (++c<CC);
+
+   if (CC==2&&C==1)
+   {
+      for (i=0;i<N;i++)
+         freq[N+i] = freq[i];
+   }
+   if (CC==1&&C==2)
+   {
+      for (i=0;i<N;i++)
+         freq[i] = HALF32(ADD32(freq[i],freq[N+i]));
+   }
+
+   /* Compute inverse MDCTs */
+   compute_inv_mdcts(mode, shortBlocks, freq, out_syn, CC, LM);
+
+   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);
+      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);
+
+   } 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) {
+      for (i=0;i<nbEBands;i++)
+         oldBandE[nbEBands+i]=oldBandE[i];
+   }
+
+   /* In case start or end were to change */
+   if (!isTransient)
+   {
+      for (i=0;i<2*nbEBands;i++)
+         oldLogE2[i] = oldLogE[i];
+      for (i=0;i<2*nbEBands;i++)
+         oldLogE[i] = oldBandE[i];
+      for (i=0;i<2*nbEBands;i++)
+         backgroundLogE[i] = MIN16(backgroundLogE[i] + M*QCONST16(0.001f,DB_SHIFT), oldBandE[i]);
+   } else {
+      for (i=0;i<2*nbEBands;i++)
+         oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
+   }
+   c=0; do
+   {
+      for (i=0;i<st->start;i++)
+      {
+         oldBandE[c*nbEBands+i]=0;
+         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
+      }
+      for (i=st->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;
+
+   /* We reuse freq[] as scratch space for the de-emphasis */
+   deemphasis(out_syn, pcm, N, CC, st->downsample, mode->preemph, st->preemph_memD, freq);
+   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);
+}
+
+#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);
+   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);
+}
+
+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);
+
+   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);
+      }
+      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;
+      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/celt/celt_encoder.c b/celt/celt_encoder.c
new file mode 100644
index 0000000..59dcc5c
--- /dev/null
+++ b/celt/celt_encoder.c
@@ -0,0 +1,2331 @@
+/* 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 overlap;
+   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 variable_duration;
+   int lfe;
+   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;
+
+   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 */
+};
+
+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]; */
+         + 3*channels*mode->nbEBands*sizeof(opus_val16);  /* opus_val16 oldBandE[channels*mode->nbEBands]; */
+                                                          /* opus_val16 oldLogE[channels*mode->nbEBands]; */
+                                                          /* opus_val16 oldLogE2[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 */
+
+int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels)
+{
+   int ret;
+   ret = opus_custom_encoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
+   if (ret != OPUS_OK)
+      return ret;
+   st->upsample = resampling_factor(sampling_rate);
+   return OPUS_OK;
+}
+
+OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
+{
+   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->overlap = mode->overlap;
+   st->stream_channels = st->channels = channels;
+
+   st->upsample = 1;
+   st->start = 0;
+   st->end = st->mode->effEBands;
+   st->signalling = 1;
+
+   st->arch = opus_select_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
+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 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;
+   /* 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);
+
+   len2=len/2;
+   tf_max = 0;
+   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] = EXTRACT16(SHR32(y,2));
+         /*printf("%f ", tmp[i]);*/
+      }
+      /*printf("\n");*/
+      /* First few samples are bad because we don't propagate the memory */
+      for (i=0;i<12;i++)
+         tmp[i] = 0;
+
+#ifdef FIXED_POINT
+      /* Normalize tmp to max range */
+      {
+         int shift=0;
+         shift = 14-celt_ilog2(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,4);
+#else
+         tmp[i] = mem0 + MULT16_16_P15(QCONST16(.0625f,15),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--)
+      {
+#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 = IMAX(0,IMIN(127,MULT16_32_Q15(tmp[i],norm))); /* Do not round to nearest */
+#else
+         id = IMAX(0,IMIN(127,(int)floor(64*norm*tmp[i]))); /* 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;
+
+   /* 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(MAX16(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 */
+int patch_transient_decision(opus_val16 *newE, opus_val16 *oldE, int nbEBands,
+      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[0] = oldE[0];
+      for (i=1;i<end;i++)
+         spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT), oldE[i]);
+   } else {
+      spread_old[0] = MAX16(oldE[0],oldE[nbEBands]);
+      for (i=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>=0;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=2;i<end-1;i++)
+      {
+         opus_val16 x1, x2;
+         x1 = MAX16(0, newE[i]);
+         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-3));
+   /*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)
+{
+   const int overlap = OVERLAP(mode);
+   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);
+      }
+   } 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;
+         for (;i<B*N;i++)
+            out[c*B*N+i] = 0;
+      } while (++c<C);
+   }
+}
+
+
+void 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];
+
+
+   Nu = N/upsample;
+   if (upsample!=1)
+   {
+      for (i=0;i<N;i++)
+         inp[i] = 0;
+   }
+   for (i=0;i<Nu;i++)
+   {
+      celt_sig x;
+
+      x = SCALEIN(pcmp[CC*i]);
+#ifndef FIXED_POINT
+      /* Replace NaNs with zeros */
+      if (!(x==x))
+         x = 0;
+#endif
+      inp[i*upsample] = x;
+   }
+
+#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]));
+   }
+#endif
+   m = *mem;
+#ifdef CUSTOM_MODES
+   if (coef[1] != 0)
+   {
+      opus_val16 coef1 = coef[1];
+      opus_val16 coef2 = coef[2];
+      for (i=0;i<N;i++)
+      {
+         opus_val16 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++)
+      {
+         celt_sig x;
+         x = SHL32(inp[i], SIG_SHIFT);
+         /* Apply pre-emphasis */
+         inp[i] = x + m;
+         m = - MULT16_32_Q15(coef0, x);
+      }
+   }
+   *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,
+      int *tf_sum, 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);
+
+   *tf_sum = 0;
+   for (i=0;i<len;i++)
+   {
+      int j, 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;
+      for (j=0;j<N;j++)
+         tmp[j] = X[tf_chan*N0 + j+(m->eBands[i]<<LM)];
+      /* 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)
+      {
+         for (j=0;j<N;j++)
+            tmp_1[j] = tmp[j];
+         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;
+      *tf_sum += (isTransient ? LM : 0) - metric[i]/2;
+      /* 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)
+{
+   int i;
+   opus_val32 diff=0;
+   int c;
+   int trim_index = 5;
+   opus_val16 trim = QCONST16(5.f, 8);
+   opus_val16 logXC, logXC2;
+   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++)
+      {
+         int j;
+         opus_val32 partial = 0;
+         for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
+            partial = MAC16_16(partial, X[j], X[N0+j]);
+         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++)
+      {
+         int j;
+         opus_val32 partial = 0;
+         for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
+            partial = MAC16_16(partial, X[j], X[N0+j]);
+         minXC = MIN16(minXC, ABS16(EXTRACT16(SHR32(partial, 18))));
+      }
+      minXC = MIN16(QCONST16(1.f, 10), ABS16(minXC));
+      /*printf ("%f\n", sum);*/
+      if (sum > QCONST16(.995f,10))
+         trim_index-=4;
+      else if (sum > QCONST16(.92f,10))
+         trim_index-=3;
+      else if (sum > QCONST16(.85f,10))
+         trim_index-=2;
+      else if (sum > QCONST16(.8f,10))
+         trim_index-=1;
+      /* 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);*/
+   if (diff > QCONST16(2.f, DB_SHIFT))
+      trim_index--;
+   if (diff > QCONST16(8.f, DB_SHIFT))
+      trim_index--;
+   if (diff < -QCONST16(4.f, DB_SHIFT))
+      trim_index++;
+   if (diff < -QCONST16(10.f, DB_SHIFT))
+      trim_index++;
+   trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8), SHR16(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), QCONST16(2.f, 8)*(analysis->tonality_slope+.05f)));
+   }
+#endif
+
+#ifdef FIXED_POINT
+   trim_index = PSHR32(trim, 8);
+#else
+   trim_index = (int)floor(.5f+trim);
+#endif
+   if (trim_index<0)
+      trim_index = 0;
+   if (trim_index>10)
+      trim_index = 10;
+   /*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);
+}
+
+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)
+{
+   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);
+   for (i=0;i<nbEBands;i++)
+      offsets[i] = 0;
+   /* 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
+      {
+         follower[c*nbEBands] = 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;
+            follower[c*nbEBands+i] = MIN16(follower[c*nbEBands+i-1]+QCONST16(1.5f,DB_SHIFT), bandLogE2[c*nbEBands+i]);
+         }
+         for (i=last-1;i>=0;i--)
+            follower[c*nbEBands+i] = MIN16(follower[c*nbEBands+i], MIN16(follower[c*nbEBands+i+1]+QCONST16(2.f,DB_SHIFT), bandLogE2[c*nbEBands+i]));
+         for (i=0;i<end;i++)
+            follower[c*nbEBands+i] = MAX16(follower[c*nbEBands+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++)
+      {
+         int width;
+         int boost;
+         int boost_bits;
+
+         if (i<8)
+            follower[i] *= 2;
+         if (i>=12)
+            follower[i] = HALF16(follower[i]);
+         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 1/4 of the bits */
+         if ((!vbr || (constrained_vbr&&!isTransient))
+               && (tot_boost+boost_bits)>>BITRES>>3 > effectiveBytes/4)
+         {
+            opus_int32 cap = ((effectiveBytes/4)<<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;
+   SAVE_STACK;
+
+   mode = st->mode;
+   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+st->overlap)+st->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);
+      /* 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);
+      pitch_index = COMBFILTER_MAXPERIOD-pitch_index;
+
+      gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD,
+            N, &pitch_index, st->prefilter_period, st->prefilter_gain);
+      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-st->overlap;
+      st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
+      OPUS_COPY(in+c*(N+st->overlap), st->in_mem+c*(st->overlap), st->overlap);
+      if (offset)
+         comb_filter(in+c*(N+st->overlap)+st->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);
+
+      comb_filter(in+c*(N+st->overlap)+st->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, st->overlap);
+      OPUS_COPY(st->in_mem+c*(st->overlap), in+c*(N+st->overlap)+N, st->overlap);
+
+      if (N>COMBFILTER_MAXPERIOD)
+      {
+         OPUS_MOVE(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_MOVE(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 variable_duration, 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);
+      /*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-(16<<LM);
+   /* Apply transient boost, compensating for average boost. */
+   tf_calibration = variable_duration==OPUS_FRAMESIZE_VARIABLE ?
+                    QCONST16(0.02f,14) : QCONST16(0.04f,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.09f;
+      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;
+   }
+#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);*/
+   }
+
+   if ((!has_surround_mask||lfe) && (constrained_vbr || bitrate<64000))
+   {
+      opus_val16 rate_factor;
+#ifdef FIXED_POINT
+      rate_factor = MAX16(0,(bitrate-32000));
+#else
+      rate_factor = MAX16(0,(1.f/32768)*(bitrate-32000));
+#endif
+      if (constrained_vbr)
+         rate_factor = MIN16(rate_factor, QCONST16(0.67f, 15));
+      target = base_target + (opus_int32)MULT16_32_Q15(rate_factor, 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;
+   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 effEnd;
+   int codedBands;
+   int tf_sum;
+   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;
+   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;
+   VARDECL(opus_val16, surround_dynalloc);
+   ALLOC_STACK;
+
+   mode = st->mode;
+   nbEBands = mode->nbEBands;
+   overlap = mode->overlap;
+   eBands = mode->eBands;
+   tf_estimate = 0;
+   if (nbCompressedBytes<2 || pcm==NULL)
+     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)
+      return OPUS_BAD_ARG;
+   M=1<<LM;
+   N = M*mode->shortMdctSize;
+
+   prefilter_mem = st->in_mem+CC*(st->overlap);
+   oldBandE = (opus_val16*)(st->in_mem+CC*(st->overlap+COMBFILTER_MAXPERIOD));
+   oldLogE = oldBandE + CC*nbEBands;
+   oldLogE2 = oldLogE + CC*nbEBands;
+
+   if (enc==NULL)
+   {
+      tell=1;
+      nbFilledBytes=0;
+   } else {
+      tell=ec_tell(enc);
+      nbFilledBytes=(tell+4)>>3;
+   }
+
+#ifdef CUSTOM_MODES
+   if (st->signalling && enc==NULL)
+   {
+      int tmp = (mode->effEBands-st->end)>>1;
+      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)
+            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;
+   }
+
+   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 = st->end;
+   if (effEnd > mode->effEBands)
+      effEnd = mode->effEBands;
+
+   ALLOC(in, CC*(N+st->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 {
+      preemphasis(pcm+c, in+c*(N+st->overlap)+st->overlap, N, CC, st->upsample,
+                  mode->preemph, st->preemph_memE+c, st->clip);
+   } while (++c<CC);
+
+
+
+   /* Find pitch period and gain */
+   {
+      int enabled;
+      int qg;
+      enabled = (st->lfe || nbAvailableBytes>12*C) && st->start==0 && !silence && !st->disable_pf
+            && st->complexity >= 5 && !(st->consec_transient && LM!=3 && st->variable_duration==OPUS_FRAMESIZE_VARIABLE);
+
+      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(st->start==0 && 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)
+   {
+      isTransient = transient_analysis(in, N+st->overlap, CC,
+            &tf_estimate, &tf_chan);
+   }
+   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);
+      compute_band_energies(mode, freq, bandE, effEnd, C, M);
+      amp2Log2(mode, effEnd, st->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);
+   if (CC==2&&C==1)
+      tf_chan = 0;
+   compute_band_energies(mode, freq, bandE, effEnd, C, M);
+
+   if (st->lfe)
+   {
+      for (i=2;i<st->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, st->end, bandE, bandLogE, C);
+
+   ALLOC(surround_dynalloc, C*nbEBands, opus_val16);
+   for(i=0;i<st->end;i++)
+      surround_dynalloc[i] = 0;
+   /* This computes how much masking takes place between surround channels */
+   if (st->start==0&&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);
+         }
+      }
+      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;
+            for(i=0;i<mask_end;i++)
+               surround_dynalloc[i] = 0;
+         } 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);
+      float frame_avg=0;
+      opus_val16 offset = shortBlocks?HALF16(SHL16(LM, DB_SHIFT)):0;
+      for(i=st->start;i<st->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 /= (st->end-st->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)
+   {
+      for (i=0;i<C*nbEBands;i++)
+         bandLogE2[i] = bandLogE[i];
+   }
+
+   /* 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)
+   {
+      if (patch_transient_decision(bandLogE, oldBandE, nbEBands, st->end, C))
+      {
+         isTransient = 1;
+         shortBlocks = M;
+         compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample);
+         compute_band_energies(mode, freq, bandE, effEnd, C, M);
+         amp2Log2(mode, effEnd, st->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 && st->start==0 && st->complexity>=2 && !st->lfe)
+   {
+      int lambda;
+      if (effectiveBytes<40)
+         lambda = 12;
+      else if (effectiveBytes<60)
+         lambda = 6;
+      else if (effectiveBytes<100)
+         lambda = 4;
+      else
+         lambda = 3;
+      lambda*=2;
+      tf_select = tf_analysis(mode, effEnd, isTransient, tf_res, lambda, X, N, LM, &tf_sum, tf_estimate, tf_chan);
+      for (i=effEnd;i<st->end;i++)
+         tf_res[i] = tf_res[effEnd-1];
+   } else {
+      tf_sum = 0;
+      for (i=0;i<st->end;i++)
+         tf_res[i] = isTransient;
+      tf_select=0;
+   }
+
+   ALLOC(error, C*nbEBands, opus_val16);
+   quant_coarse_energy(mode, st->start, st->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(st->start, st->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 (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C || st->start != 0)
+      {
+         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&&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 {
+            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, st->start, st->end, C, offsets,
+         st->lsb_depth, mode->logN, isTransient, st->vbr, st->constrained_vbr,
+         eBands, LM, effectiveBytes, &tot_boost, st->lfe, surround_dynalloc);
+   /* 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=st->start;i<st->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)
+   {
+      int effectiveRate;
+
+      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*/
+        { 16,21,23,25,27,29,31,33,35,38,42,46,50,54,58,63,68,75,84,102,130};
+      static const opus_val16 intensity_histeresis[21]=
+        {  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6,  8, 12};
+
+      /* 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);
+
+      /* Account for coarse energy */
+      effectiveRate = (8*effectiveBytes - 80)>>LM;
+
+      /* effectiveRate in kb/s */
+      effectiveRate = 2*effectiveRate/5;
+
+      st->intensity = hysteresis_decision((opus_val16)effectiveRate, intensity_thresholds, intensity_histeresis, 21, st->intensity);
+      st->intensity = IMIN(st->end,IMAX(st->start, st->intensity));
+   }
+
+   alloc_trim = 5;
+   if (tell+(6<<BITRES) <= total_bits - total_boost)
+   {
+      if (st->lfe)
+         alloc_trim = 5;
+      else
+         alloc_trim = alloc_trim_analysis(mode, X, bandLogE,
+            st->end, LM, C, N, &st->analysis, &st->stereo_saving, tf_estimate, st->intensity, surround_trim);
+      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));
+     base_target = vbr_rate - ((40*C+20)<<BITRES);
+
+     if (st->constrained_vbr)
+        base_target += (st->vbr_offset>>lm_diff);
+
+     target = compute_vbr(mode, &st->analysis, base_target, LM, st->bitrate,
+           st->lastCodedBands, C, st->intensity, st->constrained_vbr,
+           st->stereo_saving, tot_boost, tf_estimate, pitch_change, maxDepth,
+           st->variable_duration, st->lfe, st->energy_mask!=NULL, surround_masking,
+           temporal_vbr);
+
+     /* 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 - nbFilledBytes;
+
+     nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
+     nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
+     nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes) - nbFilledBytes;
+
+     /* 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+nbFilledBytes);
+     /*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 = st->end-1;
+#ifndef DISABLE_FLOAT_API
+   if (st->analysis.valid)
+   {
+      int min_bandwidth;
+      if (st->bitrate < (opus_int32)32000*C)
+         min_bandwidth = 13;
+      else if (st->bitrate < (opus_int32)48000*C)
+         min_bandwidth = 16;
+      else if (st->bitrate < (opus_int32)60000*C)
+         min_bandwidth = 18;
+      else  if (st->bitrate < (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, st->start, st->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, st->start, st->end, oldBandE, error, fine_quant, enc, C);
+
+   /* Residual quantisation */
+   ALLOC(collapse_masks, C*nbEBands, unsigned char);
+   quant_all_bands(1, mode, st->start, st->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);
+
+   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, st->start, st->end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, 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,
+               st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
+      }
+
+      if (silence)
+      {
+         for (i=0;i<C*N;i++)
+            freq[i] = 0;
+      } else {
+         /* Synthesis */
+         denormalise_bands(mode, X, freq, oldBandE, st->start, effEnd, C, M);
+      }
+
+      c=0; do {
+         OPUS_MOVE(st->syn_mem[c], st->syn_mem[c]+N, 2*MAX_PERIOD-N+overlap/2);
+      } while (++c<CC);
+
+      if (CC==2&&C==1)
+      {
+         for (i=0;i<N;i++)
+            freq[N+i] = freq[i];
+      }
+
+      c=0; do {
+         out_mem[c] = st->syn_mem[c]+2*MAX_PERIOD-N;
+      } while (++c<CC);
+
+      compute_inv_mdcts(mode, shortBlocks, freq, out_mem, CC, LM);
+
+      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, st->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, freq);
+      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) {
+      for (i=0;i<nbEBands;i++)
+         oldBandE[nbEBands+i]=oldBandE[i];
+   }
+
+   if (!isTransient)
+   {
+      for (i=0;i<CC*nbEBands;i++)
+         oldLogE2[i] = oldLogE[i];
+      for (i=0;i<CC*nbEBands;i++)
+         oldLogE[i] = oldBandE[i];
+   } 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<st->start;i++)
+      {
+         oldBandE[c*nbEBands+i]=0;
+         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
+      }
+      for (i=st->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_EXPERT_FRAME_DURATION_REQUEST:
+      {
+          opus_int32 value = va_arg(ap, opus_int32);
+          st->variable_duration = value;
+      }
+      break;
+      case OPUS_RESET_STATE:
+      {
+         int i;
+         opus_val16 *oldBandE, *oldLogE, *oldLogE2;
+         oldBandE = (opus_val16*)(st->in_mem+st->channels*(st->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_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/celt/celt_lpc.c b/celt/celt_lpc.c
index d2addbf..7ffe90a 100644
--- a/celt/celt_lpc.c
+++ b/celt/celt_lpc.c
@@ -32,6 +32,7 @@
 #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      */
@@ -87,42 +88,71 @@
 #endif
 }
 
-void celt_fir(const opus_val16 *x,
+void celt_fir(const opus_val16 *_x,
          const opus_val16 *num,
-         opus_val16 *y,
+         opus_val16 *_y,
          int N,
          int ord,
          opus_val16 *mem)
 {
    int i,j;
+   VARDECL(opus_val16, rnum);
+   VARDECL(opus_val16, x);
+   SAVE_STACK;
 
+   ALLOC(rnum, ord, opus_val16);
+   ALLOC(x, N+ord, opus_val16);
+   for(i=0;i<ord;i++)
+      rnum[i] = num[ord-i-1];
+   for(i=0;i<ord;i++)
+      x[i] = mem[ord-i-1];
+   for (i=0;i<N;i++)
+      x[i+ord]=_x[i];
+   for(i=0;i<ord;i++)
+      mem[i] = _x[N-i-1];
+#ifdef SMALL_FOOTPRINT
    for (i=0;i<N;i++)
    {
-      opus_val32 sum = SHL32(EXTEND32(x[i]), SIG_SHIFT);
+      opus_val32 sum = SHL32(EXTEND32(_x[i]), SIG_SHIFT);
       for (j=0;j<ord;j++)
       {
-         sum += MULT16_16(num[j],mem[j]);
+         sum = MAC16_16(sum,rnum[j],x[i+j]);
       }
-      for (j=ord-1;j>=1;j--)
-      {
-         mem[j]=mem[j-1];
-      }
-      mem[0] = x[i];
-      y[i] = ROUND16(sum, SIG_SHIFT);
+      _y[i] = SATURATE16(PSHR32(sum, SIG_SHIFT));
    }
+#else
+   for (i=0;i<N-3;i+=4)
+   {
+      opus_val32 sum[4]={0,0,0,0};
+      xcorr_kernel(rnum, x+i, sum, ord);
+      _y[i  ] = SATURATE16(ADD32(EXTEND32(_x[i  ]), PSHR32(sum[0], SIG_SHIFT)));
+      _y[i+1] = SATURATE16(ADD32(EXTEND32(_x[i+1]), PSHR32(sum[1], SIG_SHIFT)));
+      _y[i+2] = SATURATE16(ADD32(EXTEND32(_x[i+2]), PSHR32(sum[2], SIG_SHIFT)));
+      _y[i+3] = SATURATE16(ADD32(EXTEND32(_x[i+3]), PSHR32(sum[3], SIG_SHIFT)));
+   }
+   for (;i<N;i++)
+   {
+      opus_val32 sum = 0;
+      for (j=0;j<ord;j++)
+         sum = MAC16_16(sum,rnum[j],x[i+j]);
+      _y[i] = SATURATE16(ADD32(EXTEND32(_x[i]), PSHR32(sum, SIG_SHIFT)));
+   }
+#endif
+   RESTORE_STACK;
 }
 
-void celt_iir(const opus_val32 *x,
+void celt_iir(const opus_val32 *_x,
          const opus_val16 *den,
-         opus_val32 *y,
+         opus_val32 *_y,
          int N,
          int ord,
          opus_val16 *mem)
 {
+#ifdef SMALL_FOOTPRINT
    int i,j;
    for (i=0;i<N;i++)
    {
-      opus_val32 sum = x[i];
+      opus_val32 sum = _x[i];
       for (j=0;j<ord;j++)
       {
          sum -= MULT16_16(den[j],mem[j]);
@@ -132,11 +162,65 @@
          mem[j]=mem[j-1];
       }
       mem[0] = ROUND16(sum,SIG_SHIFT);
-      y[i] = sum;
+      _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);
+
+      /* Patch up the result to compensate for the fact that this is an IIR */
+      y[i+ord  ] = -ROUND16(sum[0],SIG_SHIFT);
+      _y[i  ] = sum[0];
+      sum[1] = MAC16_16(sum[1], y[i+ord  ], den[0]);
+      y[i+ord+1] = -ROUND16(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] = -ROUND16(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] = -ROUND16(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] = ROUND16(sum,SIG_SHIFT);
+      _y[i] = sum;
+   }
+   for(i=0;i<ord;i++)
+      mem[i] = _y[N-i-1];
+   RESTORE_STACK;
+#endif
 }
 
-void _celt_autocorr(
+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,
@@ -146,43 +230,79 @@
                   )
 {
    opus_val32 d;
-   int i;
+   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);
-   for (i=0;i<n;i++)
-      xx[i] = x[i];
-   for (i=0;i<overlap;i++)
+   if (overlap == 0)
    {
-      xx[i] = MULT16_16_Q15(x[i],window[i]);
-      xx[n-i-1] = MULT16_16_Q15(x[n-i-1],window[i]);
+      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=0;
-      int shift;
-      for(i=0;i<n;i++)
-         ac0 += SHR32(MULT16_16(xx[i],xx[i]),9);
-      ac0 += 1+n;
+      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+1)/2;
-      for(i=0;i<n;i++)
-         xx[i] = VSHR32(xx[i], shift);
+      shift = (shift)/2;
+      if (shift>0)
+      {
+         for(i=0;i<n;i++)
+            xx[i] = PSHR32(xptr[i], shift);
+         xptr = xx;
+      } else
+         shift = 0;
    }
 #endif
-   while (lag>=0)
+   celt_pitch_xcorr(xptr, xptr, ac, fastN, lag+1);
+   for (k=0;k<=lag;k++)
    {
-      for (i = lag, d = 0; i < n; i++)
-         d += xx[i] * xx[i-lag];
-      ac[lag] = d;
-      /*printf ("%f ", ac[lag]);*/
-      lag--;
+      for (i = k+fastN, d = 0; i < n; i++)
+         d = MAC16_16(d, xptr[i], xptr[i-k]);
+      ac[k] += d;
    }
-   /*printf ("\n");*/
-   ac[0] += 10;
+#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/celt/celt_lpc.h b/celt/celt_lpc.h
index 2baa77e..19279a0 100644
--- a/celt/celt_lpc.h
+++ b/celt/celt_lpc.h
@@ -48,6 +48,6 @@
          int ord,
          opus_val16 *mem);
 
-void _celt_autocorr(const opus_val16 *x, opus_val32 *ac, const opus_val16 *window, int overlap, int lag, int n);
+int _celt_autocorr(const opus_val16 *x, opus_val32 *ac, const opus_val16 *window, int overlap, int lag, int n);
 
 #endif /* PLC_H */
diff --git a/celt/cpu_support.h b/celt/cpu_support.h
new file mode 100644
index 0000000..41481fe
--- /dev/null
+++ b/celt/cpu_support.h
@@ -0,0 +1,51 @@
+/* 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
+
+#if defined(OPUS_HAVE_RTCD) && defined(ARMv4_ASM)
+#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
+
+#else
+#define OPUS_ARCHMASK 0
+
+static inline int opus_select_arch(void)
+{
+  return 0;
+}
+#endif
+
+#endif
diff --git a/celt/cwrs.c b/celt/cwrs.c
index 8edc919..28e6561 100644
--- a/celt/cwrs.c
+++ b/celt/cwrs.c
@@ -71,64 +71,6 @@
 }
 #endif
 
-#ifndef SMALL_FOOTPRINT
-
-#define MASK32 (0xFFFFFFFF)
-
-/*INV_TABLE[i] holds the multiplicative inverse of (2*i+1) mod 2**32.*/
-static const opus_uint32 INV_TABLE[53]={
-  0x00000001,0xAAAAAAAB,0xCCCCCCCD,0xB6DB6DB7,
-  0x38E38E39,0xBA2E8BA3,0xC4EC4EC5,0xEEEEEEEF,
-  0xF0F0F0F1,0x286BCA1B,0x3CF3CF3D,0xE9BD37A7,
-  0xC28F5C29,0x684BDA13,0x4F72C235,0xBDEF7BDF,
-  0x3E0F83E1,0x8AF8AF8B,0x914C1BAD,0x96F96F97,
-  0xC18F9C19,0x2FA0BE83,0xA4FA4FA5,0x677D46CF,
-  0x1A1F58D1,0xFAFAFAFB,0x8C13521D,0x586FB587,
-  0xB823EE09,0xA08AD8F3,0xC10C9715,0xBEFBEFBF,
-  0xC0FC0FC1,0x07A44C6B,0xA33F128D,0xE327A977,
-  0xC7E3F1F9,0x962FC963,0x3F2B3885,0x613716AF,
-  0x781948B1,0x2B2E43DB,0xFCFCFCFD,0x6FD0EB67,
-  0xFA3F47E9,0xD2FD2FD3,0x3F4FD3F5,0xD4E25B9F,
-  0x5F02A3A1,0xBF5A814B,0x7C32B16D,0xD3431B57,
-  0xD8FD8FD9,
-};
-
-/*Computes (_a*_b-_c)/(2*_d+1) when the quotient is known to be exact.
-  _a, _b, _c, and _d may be arbitrary so long as the arbitrary precision result
-   fits in 32 bits, but currently the table for multiplicative inverses is only
-   valid for _d<=52.*/
-static inline opus_uint32 imusdiv32odd(opus_uint32 _a,opus_uint32 _b,
- opus_uint32 _c,int _d){
-  celt_assert(_d<=52);
-  return (_a*_b-_c)*INV_TABLE[_d]&MASK32;
-}
-
-/*Computes (_a*_b-_c)/_d when the quotient is known to be exact.
-  _d does not actually have to be even, but imusdiv32odd will be faster when
-   it's odd, so you should use that instead.
-  _a and _d are assumed to be small (e.g., _a*_d fits in 32 bits; currently the
-   table for multiplicative inverses is only valid for _d<=54).
-  _b and _c may be arbitrary so long as the arbitrary precision reuslt fits in
-   32 bits.*/
-static inline opus_uint32 imusdiv32even(opus_uint32 _a,opus_uint32 _b,
- opus_uint32 _c,int _d){
-  opus_uint32 inv;
-  int           mask;
-  int           shift;
-  int           one;
-  celt_assert(_d>0);
-  celt_assert(_d<=54);
-  shift=EC_ILOG(_d^(_d-1));
-  inv=INV_TABLE[(_d-1)>>shift];
-  shift--;
-  one=1<<shift;
-  mask=one-1;
-  return (_a*(_b>>shift)-(_c>>shift)+
-   ((_a*(_b&mask)+one-(_c&mask))>>shift)-1)*inv&MASK32;
-}
-
-#endif /* SMALL_FOOTPRINT */
-
 /*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
@@ -248,46 +190,346 @@
     year=1986
   }*/
 
-#ifndef SMALL_FOOTPRINT
-/*Compute U(2,_k).
-  Note that this may be called with _k=32768 (maxK[2]+1).*/
-static inline unsigned ucwrs2(unsigned _k){
-  celt_assert(_k>0);
-  return _k+(_k-1);
+#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)
+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
+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;
 }
 
-/*Compute V(2,_k).*/
-static inline opus_uint32 ncwrs2(int _k){
+void encode_pulses(const int *_y,int _n,int _k,ec_enc *_enc){
   celt_assert(_k>0);
-  return 4*(opus_uint32)_k;
+  ec_enc_uint(_enc,icwrs(_n,_y),CELT_PVQ_V(_n,_k));
 }
 
-/*Compute U(3,_k).
-  Note that this may be called with _k=32768 (maxK[3]+1).*/
-static inline opus_uint32 ucwrs3(unsigned _k){
+static void cwrsi(int _n,int _k,opus_uint32 _i,int *_y){
+  opus_uint32 p;
+  int         s;
+  int         k0;
   celt_assert(_k>0);
-  return (2*(opus_uint32)_k-2)*_k+1;
+  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;
+      *_y++=(k0-_k+s)^s;
+    }
+    /*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;
+        *_y++=(k0-_k+s)^s;
+      }
+    }
+    _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;
+  *_y++=(k0-_k+s)^s;
+  /*_n==1*/
+  s=-(int)_i;
+  *_y=(_k+s)^s;
 }
 
-/*Compute V(3,_k).*/
-static inline opus_uint32 ncwrs3(int _k){
-  celt_assert(_k>0);
-  return 2*(2*(unsigned)_k*(opus_uint32)_k+1);
+void decode_pulses(int *_y,int _n,int _k,ec_dec *_dec){
+  cwrsi(_n,_k,ec_dec_uint(_dec,CELT_PVQ_V(_n,_k)),_y);
 }
 
-/*Compute U(4,_k).*/
-static inline opus_uint32 ucwrs4(int _k){
-  celt_assert(_k>0);
-  return imusdiv32odd(2*_k,(2*_k-3)*(opus_uint32)_k+4,3,1);
-}
-
-/*Compute V(4,_k).*/
-static inline opus_uint32 ncwrs4(int _k){
-  celt_assert(_k>0);
-  return ((_k*(opus_uint32)_k+2)*_k)/3<<3;
-}
-
-#endif /* SMALL_FOOTPRINT */
+#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].
@@ -332,125 +574,18 @@
   celt_assert(len>=3);
   _u[0]=0;
   _u[1]=um2=1;
-#ifndef SMALL_FOOTPRINT
-  /*_k>52 doesn't work in the false branch due to the limits of INV_TABLE,
-    but _k isn't tested here because k<=52 for n=7*/
-  if(_n<=6)
-#endif
-  {
-    /*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);
-  }
-#ifndef SMALL_FOOTPRINT
-  else{
-    opus_uint32 um1;
-    opus_uint32 n2m1;
-    _u[2]=n2m1=um1=(_n<<1)-1;
-    for(k=3;k<len;k++){
-      /*U(N,K) = ((2*N-1)*U(N,K-1)-U(N,K-2))/(K-1) + U(N,K-2)*/
-      _u[k]=um2=imusdiv32even(n2m1,um1,um2,k-1)+um2;
-      if(++k>=len)break;
-      _u[k]=um1=imusdiv32odd(n2m1,um2,um1,(k-1)>>1)+um1;
-    }
-  }
-#endif /* SMALL_FOOTPRINT */
+  /*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];
 }
 
-#ifndef SMALL_FOOTPRINT
-
-/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
-   set of size 1 with associated sign bits.
-  _y: Returns the vector of pulses.*/
-static inline void cwrsi1(int _k,opus_uint32 _i,int *_y){
-  int s;
-  s=-(int)_i;
-  _y[0]=(_k+s)^s;
-}
-
-/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
-   set of size 2 with associated sign bits.
-  _y: Returns the vector of pulses.*/
-static inline void cwrsi2(int _k,opus_uint32 _i,int *_y){
-  opus_uint32 p;
-  int           s;
-  int           yj;
-  p=ucwrs2(_k+1U);
-  s=-(_i>=p);
-  _i-=p&s;
-  yj=_k;
-  _k=(_i+1)>>1;
-  p=_k?ucwrs2(_k):0;
-  _i-=p;
-  yj-=_k;
-  _y[0]=(yj+s)^s;
-  cwrsi1(_k,_i,_y+1);
-}
-
-/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
-   set of size 3 with associated sign bits.
-  _y: Returns the vector of pulses.*/
-static void cwrsi3(int _k,opus_uint32 _i,int *_y){
-  opus_uint32 p;
-  int           s;
-  int           yj;
-  p=ucwrs3(_k+1U);
-  s=-(_i>=p);
-  _i-=p&s;
-  yj=_k;
-  /*Finds the maximum _k such that ucwrs3(_k)<=_i (tested for all
-     _i<2147418113=U(3,32768)).*/
-  _k=_i>0?(isqrt32(2*_i-1)+1)>>1:0;
-  p=_k?ucwrs3(_k):0;
-  _i-=p;
-  yj-=_k;
-  _y[0]=(yj+s)^s;
-  cwrsi2(_k,_i,_y+1);
-}
-
-/*Returns the _i'th combination of _k elements (at most 1172) chosen from a set
-   of size 4 with associated sign bits.
-  _y: Returns the vector of pulses.*/
-static void cwrsi4(int _k,opus_uint32 _i,int *_y){
-  opus_uint32 p;
-  int           s;
-  int           yj;
-  int           kl;
-  int           kr;
-  p=ucwrs4(_k+1);
-  s=-(_i>=p);
-  _i-=p&s;
-  yj=_k;
-  /*We could solve a cubic for k here, but the form of the direct solution does
-     not lend itself well to exact integer arithmetic.
-    Instead we do a binary search on U(4,K).*/
-  kl=0;
-  kr=_k;
-  for(;;){
-    _k=(kl+kr)>>1;
-    p=_k?ucwrs4(_k):0;
-    if(p<_i){
-      if(_k>=kr)break;
-      kl=_k+1;
-    }
-    else if(p>_i)kr=_k-1;
-    else break;
-  }
-  _i-=p;
-  yj-=_k;
-  _y[0]=(yj+s)^s;
-  cwrsi3(_k,_i,_y+1);
-}
-
-#endif /* SMALL_FOOTPRINT */
-
 /*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.
@@ -487,55 +622,6 @@
   return _y[0]<0;
 }
 
-#ifndef SMALL_FOOTPRINT
-
-/*Returns the index of the given combination of K elements chosen from a set
-   of size 2 with associated sign bits.
-  _y: The vector of pulses, whose sum of absolute values is K.
-  _k: Returns K.*/
-static inline opus_uint32 icwrs2(const int *_y,int *_k){
-  opus_uint32 i;
-  int           k;
-  i=icwrs1(_y+1,&k);
-  i+=k?ucwrs2(k):0;
-  k+=abs(_y[0]);
-  if(_y[0]<0)i+=ucwrs2(k+1U);
-  *_k=k;
-  return i;
-}
-
-/*Returns the index of the given combination of K elements chosen from a set
-   of size 3 with associated sign bits.
-  _y: The vector of pulses, whose sum of absolute values is K.
-  _k: Returns K.*/
-static inline opus_uint32 icwrs3(const int *_y,int *_k){
-  opus_uint32 i;
-  int           k;
-  i=icwrs2(_y+1,&k);
-  i+=k?ucwrs3(k):0;
-  k+=abs(_y[0]);
-  if(_y[0]<0)i+=ucwrs3(k+1U);
-  *_k=k;
-  return i;
-}
-
-/*Returns the index of the given combination of K elements chosen from a set
-   of size 4 with associated sign bits.
-  _y: The vector of pulses, whose sum of absolute values is K.
-  _k: Returns K.*/
-static inline opus_uint32 icwrs4(const int *_y,int *_k){
-  opus_uint32 i;
-  int           k;
-  i=icwrs3(_y+1,&k);
-  i+=k?ucwrs4(k):0;
-  k+=abs(_y[0]);
-  if(_y[0]<0)i+=ucwrs4(k+1);
-  *_k=k;
-  return i;
-}
-
-#endif /* SMALL_FOOTPRINT */
-
 /*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.
@@ -543,8 +629,8 @@
 static inline opus_uint32 icwrs(int _n,int _k,opus_uint32 *_nc,const int *_y,
  opus_uint32 *_u){
   opus_uint32 i;
-  int           j;
-  int           k;
+  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;
@@ -589,57 +675,23 @@
 
 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);
-#ifndef SMALL_FOOTPRINT
-  switch(_n){
-    case 2:{
-      i=icwrs2(_y,&_k);
-      ec_enc_uint(_enc,i,ncwrs2(_k));
-    }break;
-    case 3:{
-      i=icwrs3(_y,&_k);
-      ec_enc_uint(_enc,i,ncwrs3(_k));
-    }break;
-    case 4:{
-      i=icwrs4(_y,&_k);
-      ec_enc_uint(_enc,i,ncwrs4(_k));
-    }break;
-     default:
-    {
-#endif
-      VARDECL(opus_uint32,u);
-      opus_uint32 nc;
-      SAVE_STACK;
-      ALLOC(u,_k+2U,opus_uint32);
-      i=icwrs(_n,_k,&nc,_y,u);
-      ec_enc_uint(_enc,i,nc);
-      RESTORE_STACK;
-#ifndef SMALL_FOOTPRINT
-    }
-    break;
-  }
-#endif
+  ALLOC(u,_k+2U,opus_uint32);
+  i=icwrs(_n,_k,&nc,_y,u);
+  ec_enc_uint(_enc,i,nc);
+  RESTORE_STACK;
 }
 
-void decode_pulses(int *_y,int _n,int _k,ec_dec *_dec)
-{
+void decode_pulses(int *_y,int _n,int _k,ec_dec *_dec){
+  VARDECL(opus_uint32,u);
+  SAVE_STACK;
   celt_assert(_k>0);
-#ifndef SMALL_FOOTPRINT
-   switch(_n){
-    case 2:cwrsi2(_k,ec_dec_uint(_dec,ncwrs2(_k)),_y);break;
-    case 3:cwrsi3(_k,ec_dec_uint(_dec,ncwrs3(_k)),_y);break;
-    case 4:cwrsi4(_k,ec_dec_uint(_dec,ncwrs4(_k)),_y);break;
-    default:
-    {
-#endif
-      VARDECL(opus_uint32,u);
-      SAVE_STACK;
-      ALLOC(u,_k+2U,opus_uint32);
-      cwrsi(_n,_k,ec_dec_uint(_dec,ncwrs_urow(_n,_k,u)),_y,u);
-      RESTORE_STACK;
-#ifndef SMALL_FOOTPRINT
-    }
-    break;
-  }
-#endif
+  ALLOC(u,_k+2U,opus_uint32);
+  cwrsi(_n,_k,ec_dec_uint(_dec,ncwrs_urow(_n,_k,u)),_y,u);
+  RESTORE_STACK;
 }
+
+#endif /* SMALL_FOOTPRINT */
diff --git a/celt/dump_modes/Makefile b/celt/dump_modes/Makefile
new file mode 100644
index 0000000..371a7d4
--- /dev/null
+++ b/celt/dump_modes/Makefile
@@ -0,0 +1,10 @@
+CFLAGS=-O2 -Wall -Wextra -DHAVE_CONFIG_H
+INCLUDES=-I../ -I../.. -I../../include
+
+all: dump_modes
+
+dump_modes:
+	$(CC) $(CFLAGS) $(INCLUDES) -DCUSTOM_MODES dump_modes.c ../modes.c ../cwrs.c ../rate.c ../entenc.c ../entdec.c ../mathops.c ../mdct.c ../kiss_fft.c -o dump_modes -lm 
+
+clean:
+	rm -f dump_modes
diff --git a/celt/dump_modes/dump_modes.c b/celt/dump_modes/dump_modes.c
new file mode 100644
index 0000000..8c07e19
--- /dev/null
+++ b/celt/dump_modes/dump_modes.c
@@ -0,0 +1,329 @@
+/* Copyright (c) 2008 CSIRO
+   Copyright (c) 2008-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 <stdlib.h>
+#include <stdio.h>
+#include "modes.h"
+#include "celt.h"
+#include "rate.h"
+
+#define INT16 "%d"
+#define INT32 "%d"
+#define FLOAT "%#0.8gf"
+
+#ifdef FIXED_POINT
+#define WORD16 INT16
+#define WORD32 INT32
+#else
+#define WORD16 FLOAT
+#define WORD32 FLOAT
+#endif
+
+void dump_modes(FILE *file, CELTMode **modes, int nb_modes)
+{
+   int i, j, k;
+   fprintf(file, "/* The contents of this file was automatically generated by dump_modes.c\n");
+   fprintf(file, "   with arguments:");
+   for (i=0;i<nb_modes;i++)
+   {
+      CELTMode *mode = modes[i];
+      fprintf(file, " %d %d",mode->Fs,mode->shortMdctSize*mode->nbShortMdcts);
+   }
+   fprintf(file, "\n   It contains static definitions for some pre-defined modes. */\n");
+   fprintf(file, "#include \"modes.h\"\n");
+   fprintf(file, "#include \"rate.h\"\n");
+
+   fprintf(file, "\n");
+
+   for (i=0;i<nb_modes;i++)
+   {
+      CELTMode *mode = modes[i];
+      int mdctSize;
+      int standard, framerate;
+
+      mdctSize = mode->shortMdctSize*mode->nbShortMdcts;
+      standard = (mode->Fs == 400*(opus_int32)mode->shortMdctSize);
+      framerate = mode->Fs/mode->shortMdctSize;
+
+      if (!standard)
+      {
+         fprintf(file, "#ifndef DEF_EBANDS%d_%d\n", mode->Fs, mdctSize);
+         fprintf(file, "#define DEF_EBANDS%d_%d\n", mode->Fs, mdctSize);
+         fprintf (file, "static const opus_int16 eBands%d_%d[%d] = {\n", mode->Fs, mdctSize, mode->nbEBands+2);
+         for (j=0;j<mode->nbEBands+2;j++)
+            fprintf (file, "%d, ", mode->eBands[j]);
+         fprintf (file, "};\n");
+         fprintf(file, "#endif\n");
+         fprintf(file, "\n");
+      }
+
+      fprintf(file, "#ifndef DEF_WINDOW%d\n", mode->overlap);
+      fprintf(file, "#define DEF_WINDOW%d\n", mode->overlap);
+      fprintf (file, "static const opus_val16 window%d[%d] = {\n", mode->overlap, mode->overlap);
+      for (j=0;j<mode->overlap;j++)
+         fprintf (file, WORD16 ",%c", mode->window[j],(j+6)%5==0?'\n':' ');
+      fprintf (file, "};\n");
+      fprintf(file, "#endif\n");
+      fprintf(file, "\n");
+
+      if (!standard)
+      {
+         fprintf(file, "#ifndef DEF_ALLOC_VECTORS%d_%d\n", mode->Fs, mdctSize);
+         fprintf(file, "#define DEF_ALLOC_VECTORS%d_%d\n", mode->Fs, mdctSize);
+         fprintf (file, "static const unsigned char allocVectors%d_%d[%d] = {\n", mode->Fs, mdctSize, mode->nbEBands*mode->nbAllocVectors);
+         for (j=0;j<mode->nbAllocVectors;j++)
+         {
+            for (k=0;k<mode->nbEBands;k++)
+               fprintf (file, "%2d, ", mode->allocVectors[j*mode->nbEBands+k]);
+            fprintf (file, "\n");
+         }
+         fprintf (file, "};\n");
+         fprintf(file, "#endif\n");
+         fprintf(file, "\n");
+      }
+
+      fprintf(file, "#ifndef DEF_LOGN%d\n", framerate);
+      fprintf(file, "#define DEF_LOGN%d\n", framerate);
+      fprintf (file, "static const opus_int16 logN%d[%d] = {\n", framerate, mode->nbEBands);
+      for (j=0;j<mode->nbEBands;j++)
+         fprintf (file, "%d, ", mode->logN[j]);
+      fprintf (file, "};\n");
+      fprintf(file, "#endif\n");
+      fprintf(file, "\n");
+
+      /* Pulse cache */
+      fprintf(file, "#ifndef DEF_PULSE_CACHE%d\n", mode->Fs/mdctSize);
+      fprintf(file, "#define DEF_PULSE_CACHE%d\n", mode->Fs/mdctSize);
+      fprintf (file, "static const opus_int16 cache_index%d[%d] = {\n", mode->Fs/mdctSize, (mode->maxLM+2)*mode->nbEBands);
+      for (j=0;j<mode->nbEBands*(mode->maxLM+2);j++)
+         fprintf (file, "%d,%c", mode->cache.index[j],(j+16)%15==0?'\n':' ');
+      fprintf (file, "};\n");
+      fprintf (file, "static const unsigned char cache_bits%d[%d] = {\n", mode->Fs/mdctSize, mode->cache.size);
+      for (j=0;j<mode->cache.size;j++)
+         fprintf (file, "%d,%c", mode->cache.bits[j],(j+16)%15==0?'\n':' ');
+      fprintf (file, "};\n");
+      fprintf (file, "static const unsigned char cache_caps%d[%d] = {\n", mode->Fs/mdctSize, (mode->maxLM+1)*2*mode->nbEBands);
+      for (j=0;j<(mode->maxLM+1)*2*mode->nbEBands;j++)
+         fprintf (file, "%d,%c", mode->cache.caps[j],(j+16)%15==0?'\n':' ');
+      fprintf (file, "};\n");
+
+      fprintf(file, "#endif\n");
+      fprintf(file, "\n");
+
+      /* FFT twiddles */
+      fprintf(file, "#ifndef FFT_TWIDDLES%d_%d\n", mode->Fs, mdctSize);
+      fprintf(file, "#define FFT_TWIDDLES%d_%d\n", mode->Fs, mdctSize);
+      fprintf (file, "static const kiss_twiddle_cpx fft_twiddles%d_%d[%d] = {\n",
+            mode->Fs, mdctSize, mode->mdct.kfft[0]->nfft);
+      for (j=0;j<mode->mdct.kfft[0]->nfft;j++)
+         fprintf (file, "{" WORD16 ", " WORD16 "},%c", mode->mdct.kfft[0]->twiddles[j].r, mode->mdct.kfft[0]->twiddles[j].i,(j+3)%2==0?'\n':' ');
+      fprintf (file, "};\n");
+
+      /* FFT Bitrev tables */
+      for (k=0;k<=mode->mdct.maxshift;k++)
+      {
+         fprintf(file, "#ifndef FFT_BITREV%d\n", mode->mdct.kfft[k]->nfft);
+         fprintf(file, "#define FFT_BITREV%d\n", mode->mdct.kfft[k]->nfft);
+         fprintf (file, "static const opus_int16 fft_bitrev%d[%d] = {\n",
+               mode->mdct.kfft[k]->nfft, mode->mdct.kfft[k]->nfft);
+         for (j=0;j<mode->mdct.kfft[k]->nfft;j++)
+            fprintf (file, "%d,%c", mode->mdct.kfft[k]->bitrev[j],(j+16)%15==0?'\n':' ');
+         fprintf (file, "};\n");
+
+         fprintf(file, "#endif\n");
+         fprintf(file, "\n");
+      }
+
+      /* FFT States */
+      for (k=0;k<=mode->mdct.maxshift;k++)
+      {
+         fprintf(file, "#ifndef FFT_STATE%d_%d_%d\n", mode->Fs, mdctSize, k);
+         fprintf(file, "#define FFT_STATE%d_%d_%d\n", mode->Fs, mdctSize, k);
+         fprintf (file, "static const kiss_fft_state fft_state%d_%d_%d = {\n",
+               mode->Fs, mdctSize, k);
+         fprintf (file, "%d,\t/* nfft */\n", mode->mdct.kfft[k]->nfft);
+#ifndef FIXED_POINT
+         fprintf (file, "%0.9ff,\t/* scale */\n", mode->mdct.kfft[k]->scale);
+#endif
+         fprintf (file, "%d,\t/* shift */\n", mode->mdct.kfft[k]->shift);
+         fprintf (file, "{");
+         for (j=0;j<2*MAXFACTORS;j++)
+            fprintf (file, "%d, ", mode->mdct.kfft[k]->factors[j]);
+         fprintf (file, "},\t/* factors */\n");
+         fprintf (file, "fft_bitrev%d,\t/* bitrev */\n", mode->mdct.kfft[k]->nfft);
+         fprintf (file, "fft_twiddles%d_%d,\t/* bitrev */\n", mode->Fs, mdctSize);
+         fprintf (file, "};\n");
+
+         fprintf(file, "#endif\n");
+         fprintf(file, "\n");
+      }
+
+      fprintf(file, "#endif\n");
+      fprintf(file, "\n");
+
+      /* MDCT twiddles */
+      fprintf(file, "#ifndef MDCT_TWIDDLES%d\n", mdctSize);
+      fprintf(file, "#define MDCT_TWIDDLES%d\n", mdctSize);
+      fprintf (file, "static const opus_val16 mdct_twiddles%d[%d] = {\n",
+            mdctSize, mode->mdct.n/4+1);
+      for (j=0;j<=mode->mdct.n/4;j++)
+         fprintf (file, WORD16 ",%c", mode->mdct.trig[j],(j+6)%5==0?'\n':' ');
+      fprintf (file, "};\n");
+
+      fprintf(file, "#endif\n");
+      fprintf(file, "\n");
+
+
+      /* Print the actual mode data */
+      fprintf(file, "static const CELTMode mode%d_%d_%d = {\n", mode->Fs, mdctSize, mode->overlap);
+      fprintf(file, INT32 ",\t/* Fs */\n", mode->Fs);
+      fprintf(file, "%d,\t/* overlap */\n", mode->overlap);
+      fprintf(file, "%d,\t/* nbEBands */\n", mode->nbEBands);
+      fprintf(file, "%d,\t/* effEBands */\n", mode->effEBands);
+      fprintf(file, "{");
+      for (j=0;j<4;j++)
+         fprintf(file, WORD16 ", ", mode->preemph[j]);
+      fprintf(file, "},\t/* preemph */\n");
+      if (standard)
+         fprintf(file, "eband5ms,\t/* eBands */\n");
+      else
+         fprintf(file, "eBands%d_%d,\t/* eBands */\n", mode->Fs, mdctSize);
+
+      fprintf(file, "%d,\t/* maxLM */\n", mode->maxLM);
+      fprintf(file, "%d,\t/* nbShortMdcts */\n", mode->nbShortMdcts);
+      fprintf(file, "%d,\t/* shortMdctSize */\n", mode->shortMdctSize);
+
+      fprintf(file, "%d,\t/* nbAllocVectors */\n", mode->nbAllocVectors);
+      if (standard)
+         fprintf(file, "band_allocation,\t/* allocVectors */\n");
+      else
+         fprintf(file, "allocVectors%d_%d,\t/* allocVectors */\n", mode->Fs, mdctSize);
+
+      fprintf(file, "logN%d,\t/* logN */\n", framerate);
+      fprintf(file, "window%d,\t/* window */\n", mode->overlap);
+      fprintf(file, "{%d, %d, {", mode->mdct.n, mode->mdct.maxshift);
+      for (k=0;k<=mode->mdct.maxshift;k++)
+         fprintf(file, "&fft_state%d_%d_%d, ", mode->Fs, mdctSize, k);
+      fprintf (file, "}, mdct_twiddles%d},\t/* mdct */\n", mdctSize);
+
+      fprintf(file, "{%d, cache_index%d, cache_bits%d, cache_caps%d},\t/* cache */\n",
+            mode->cache.size, mode->Fs/mdctSize, mode->Fs/mdctSize, mode->Fs/mdctSize);
+      fprintf(file, "};\n");
+   }
+   fprintf(file, "\n");
+   fprintf(file, "/* List of all the available modes */\n");
+   fprintf(file, "#define TOTAL_MODES %d\n", nb_modes);
+   fprintf(file, "static const CELTMode * const static_mode_list[TOTAL_MODES] = {\n");
+   for (i=0;i<nb_modes;i++)
+   {
+      CELTMode *mode = modes[i];
+      int mdctSize;
+      mdctSize = mode->shortMdctSize*mode->nbShortMdcts;
+      fprintf(file, "&mode%d_%d_%d,\n", mode->Fs, mdctSize, mode->overlap);
+   }
+   fprintf(file, "};\n");
+}
+
+void dump_header(FILE *file, CELTMode **modes, int nb_modes)
+{
+   int i;
+   int channels = 0;
+   int frame_size = 0;
+   int overlap = 0;
+   fprintf (file, "/* This header file is generated automatically*/\n");
+   for (i=0;i<nb_modes;i++)
+   {
+      CELTMode *mode = modes[i];
+      if (frame_size==0)
+         frame_size = mode->shortMdctSize*mode->nbShortMdcts;
+      else if (frame_size != mode->shortMdctSize*mode->nbShortMdcts)
+         frame_size = -1;
+      if (overlap==0)
+         overlap = mode->overlap;
+      else if (overlap != mode->overlap)
+         overlap = -1;
+   }
+   if (channels>0)
+   {
+      fprintf (file, "#define CHANNELS(mode) %d\n", channels);
+      if (channels==1)
+         fprintf (file, "#define DISABLE_STEREO\n");
+   }
+   if (frame_size>0)
+   {
+      fprintf (file, "#define FRAMESIZE(mode) %d\n", frame_size);
+   }
+   if (overlap>0)
+   {
+      fprintf (file, "#define OVERLAP(mode) %d\n", overlap);
+   }
+}
+
+#ifdef FIXED_POINT
+#define BASENAME "static_modes_fixed"
+#else
+#define BASENAME "static_modes_float"
+#endif
+
+int main(int argc, char **argv)
+{
+   int i, nb;
+   FILE *file;
+   CELTMode **m;
+   if (argc%2 != 1 || argc<3)
+   {
+      fprintf (stderr, "Usage: %s rate frame_size [rate frame_size] [rate frame_size]...\n",argv[0]);
+      return 1;
+   }
+   nb = (argc-1)/2;
+   m = malloc(nb*sizeof(CELTMode*));
+   for (i=0;i<nb;i++)
+   {
+      int Fs, frame;
+      Fs      = atoi(argv[2*i+1]);
+      frame   = atoi(argv[2*i+2]);
+      m[i] = opus_custom_mode_create(Fs, frame, NULL);
+      if (m[i]==NULL)
+      {
+         fprintf(stderr,"Error creating mode with Fs=%s, frame_size=%s\n",
+               argv[2*i+1],argv[2*i+2]);
+         return EXIT_FAILURE;
+      }
+   }
+   file = fopen(BASENAME ".h", "w");
+   dump_modes(file, m, nb);
+   fclose(file);
+   for (i=0;i<nb;i++)
+      opus_custom_mode_destroy(m[i]);
+   free(m);
+   return 0;
+}
diff --git a/celt/entdec.c b/celt/entdec.c
index 75e3e45..3c26468 100644
--- a/celt/entdec.c
+++ b/celt/entdec.c
@@ -85,7 +85,7 @@
    number=3,
    pages="256--294",
    month=Jul,
-   URL="http://www.stanford.edu/class/ee398/handouts/papers/Moffat98ArithmCoding.pdf"
+   URL="http://www.stanford.edu/class/ee398a/handouts/papers/Moffat98ArithmCoding.pdf"
   }*/
 
 static int ec_read_byte(ec_dec *_this){
diff --git a/celt/fixed_c5x.h b/celt/fixed_c5x.h
new file mode 100644
index 0000000..156ba45
--- /dev/null
+++ b/celt/fixed_c5x.h
@@ -0,0 +1,79 @@
+/* Copyright (C) 2003 Jean-Marc Valin */
+/**
+   @file fixed_c5x.h
+   @brief Fixed-point operations for the TI C5x DSP family
+*/
+/*
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions
+   are met:
+
+   - Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef FIXED_C5X_H
+#define FIXED_C5X_H
+
+#include "dsplib.h"
+
+#undef IMUL32
+static inline long IMUL32(long i, long j)
+{
+   long ac0, ac1;
+   ac0 = _lmpy(i>>16,j);
+   ac1 = ac0 + _lmpy(i,j>>16);
+   return _lmpyu(i,j) + (ac1<<16);
+}
+
+#undef MAX16
+#define MAX16(a,b) _max(a,b)
+
+#undef MIN16
+#define MIN16(a,b) _min(a,b)
+
+#undef MAX32
+#define MAX32(a,b) _lmax(a,b)
+
+#undef MIN32
+#define MIN32(a,b) _lmin(a,b)
+
+#undef VSHR32
+#define VSHR32(a, shift) _lshl(a,-(shift))
+
+#undef MULT16_16_Q15
+#define MULT16_16_Q15(a,b) (_smpy(a,b))
+
+#undef MULT16_16SU
+#define MULT16_16SU(a,b) _lmpysu(a,b)
+
+#undef MULT_16_16
+#define MULT_16_16(a,b) _lmpy(a,b)
+
+/* FIXME: This is technically incorrect and is bound to cause problems. Is there any cleaner solution? */
+#undef MULT16_32_Q15
+#define MULT16_32_Q15(a,b) ADD32(SHL(MULT16_16((a),SHR((b),16)),1), SHR(MULT16_16SU((a),(b)),15))
+
+#define celt_ilog2(x) (30 - _lnorm(x))
+#define OVERRIDE_CELT_ILOG2
+
+#define celt_maxabs16(x, len) MAX32(EXTEND32(maxval((DATA *)x, len)),-EXTEND32(minval((DATA *)x, len)))
+#define OVERRIDE_CELT_MAXABS16
+
+#endif /* FIXED_C5X_H */
diff --git a/celt/fixed_c6x.h b/celt/fixed_c6x.h
new file mode 100644
index 0000000..bb6ad92
--- /dev/null
+++ b/celt/fixed_c6x.h
@@ -0,0 +1,70 @@
+/* Copyright (C) 2008 CSIRO */
+/**
+   @file fixed_c6x.h
+   @brief Fixed-point operations for the TI C6x DSP family
+*/
+/*
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions
+   are met:
+
+   - Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef FIXED_C6X_H
+#define FIXED_C6X_H
+
+#undef MULT16_16SU
+#define MULT16_16SU(a,b) _mpysu(a,b)
+
+#undef MULT_16_16
+#define MULT_16_16(a,b) _mpy(a,b)
+
+#define celt_ilog2(x) (30 - _norm(x))
+#define OVERRIDE_CELT_ILOG2
+
+#undef MULT16_32_Q15
+#define MULT16_32_Q15(a,b) (_mpylill(a, b) >> 15)
+
+#if 0
+#include "dsplib.h"
+
+#undef MAX16
+#define MAX16(a,b) _max(a,b)
+
+#undef MIN16
+#define MIN16(a,b) _min(a,b)
+
+#undef MAX32
+#define MAX32(a,b) _lmax(a,b)
+
+#undef MIN32
+#define MIN32(a,b) _lmin(a,b)
+
+#undef VSHR32
+#define VSHR32(a, shift) _lshl(a,-(shift))
+
+#undef MULT16_16_Q15
+#define MULT16_16_Q15(a,b) (_smpy(a,b))
+
+#define celt_maxabs16(x, len) MAX32(EXTEND32(maxval((DATA *)x, len)),-EXTEND32(minval((DATA *)x, len)))
+#define OVERRIDE_CELT_MAXABS16
+
+#endif /* FIXED_C6X_H */
diff --git a/celt/fixed_generic.h b/celt/fixed_generic.h
index 71e28d6..657e67c 100644
--- a/celt/fixed_generic.h
+++ b/celt/fixed_generic.h
@@ -84,6 +84,8 @@
 #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))))
 /** Divide by two */
@@ -108,10 +110,13 @@
 
 /** 16x16 multiply-add where the result fits in 32 bits */
 #define MAC16_16(c,a,b) (ADD32((c),MULT16_16((a),(b))))
-/** 16x32 multiply-add, followed by a 15-bit shift right. Results fits in 32 bits */
+/** 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)))
 
 #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))
diff --git a/celt/kiss_fft.c b/celt/kiss_fft.c
index dcd6968..ad706c7 100644
--- a/celt/kiss_fft.c
+++ b/celt/kiss_fft.c
@@ -40,7 +40,6 @@
 #include "os_support.h"
 #include "mathops.h"
 #include "stack_alloc.h"
-#include "os_support.h"
 
 /* The guts header contains all the multiplication and addition macros that are defined for
    complex numbers.  It also delares the kf_ internal functions.
@@ -142,8 +141,6 @@
          C_ADDTO(*Fout, scratch[1]);
          C_ADD( scratch[3] , scratch[0] , scratch[2] );
          C_SUB( scratch[4] , scratch[0] , scratch[2] );
-         Fout[m2].r = PSHR32(Fout[m2].r, 2);
-         Fout[m2].i = PSHR32(Fout[m2].i, 2);
          C_SUB( Fout[m2], *Fout, scratch[3] );
          tw1 += fstride;
          tw2 += fstride*2;
diff --git a/celt/mathops.c b/celt/mathops.c
index ce472c9..21fd942 100644
--- a/celt/mathops.c
+++ b/celt/mathops.c
@@ -123,6 +123,8 @@
    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;
diff --git a/celt/mathops.h b/celt/mathops.h
index 4e97795..7e7d906 100644
--- a/celt/mathops.h
+++ b/celt/mathops.h
@@ -43,6 +43,41 @@
 
 unsigned isqrt32(opus_uint32 _val);
 
+#ifndef OVERRIDE_CELT_MAXABS16
+static 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 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 PI 3.141592653f
@@ -117,27 +152,6 @@
 }
 #endif
 
-#ifndef OVERRIDE_CELT_MAXABS16
-static inline opus_val16 celt_maxabs16(opus_val16 *x, int len)
-{
-   int i;
-   opus_val16 maxval = 0;
-   for (i=0;i<len;i++)
-      maxval = MAX16(maxval, ABS16(x[i]));
-   return maxval;
-}
-#endif
-
-#ifndef OVERRIDE_CELT_MAXABS32
-static inline opus_val32 celt_maxabs32(opus_val32 *x, int len)
-{
-   int i;
-   opus_val32 maxval = 0;
-   for (i=0;i<len;i++)
-      maxval = MAX32(maxval, ABS32(x[i]));
-   return maxval;
-}
-#endif
 
 /** Integer log in base2. Defined for zero, but not for negative numbers */
 static inline opus_int16 celt_zlog2(opus_val32 x)
@@ -151,6 +165,7 @@
 
 opus_val16 celt_cos_norm(opus_val32 x);
 
+/** Base-2 logarithm approximation (log2(x)). (Q14 input, Q10 output) */
 static inline opus_val16 celt_log2(opus_val32 x)
 {
    int i;
@@ -176,6 +191,13 @@
 #define D1 22804
 #define D2 14819
 #define D3 10204
+
+static 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 inline opus_val32 celt_exp2(opus_val16 x)
 {
@@ -186,8 +208,7 @@
       return 0x7f000000;
    else if (integer < -15)
       return 0;
-   frac = SHL16(x-SHL16(integer,10),4);
-   frac = ADD16(D0, MULT16_16_Q15(frac, ADD16(D1, MULT16_16_Q15(frac, ADD16(D2 , MULT16_16_Q15(D3,frac))))));
+   frac = celt_exp2_frac(x-SHL16(integer,10));
    return VSHR32(EXTEND32(frac), -integer-2);
 }
 
diff --git a/celt/mdct.c b/celt/mdct.c
index 16a36c6..90a214a 100644
--- a/celt/mdct.c
+++ b/celt/mdct.c
@@ -109,12 +109,14 @@
    int N, N2, N4;
    kiss_twiddle_scalar sine;
    VARDECL(kiss_fft_scalar, f);
+   VARDECL(kiss_fft_scalar, f2);
    SAVE_STACK;
    N = l->n;
    N >>= shift;
    N2 = N>>1;
    N4 = N>>2;
    ALLOC(f, N2, kiss_fft_scalar);
+   ALLOC(f2, N2, kiss_fft_scalar);
    /* sin(x) ~= x here */
 #ifdef FIXED_POINT
    sine = TRIG_UPSCALE*(QCONST16(0.7853981f, 15)+N2)/N;
@@ -131,7 +133,7 @@
       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>>2);i++)
+      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);
@@ -143,7 +145,7 @@
       }
       wp1 = window;
       wp2 = window+overlap-1;
-      for(;i<N4-(overlap>>2);i++)
+      for(;i<N4-((overlap+3)>>2);i++)
       {
          /* Real part arranged as a-bR, Imag part arranged as -c-dR */
          *yp++ = *xp2;
@@ -180,12 +182,12 @@
    }
 
    /* N/4 complex FFT, down-scales by 4/N */
-   opus_fft(l->kfft[shift], (kiss_fft_cpx *)f, (kiss_fft_cpx *)in);
+   opus_fft(l->kfft[shift], (kiss_fft_cpx *)f, (kiss_fft_cpx *)f2);
 
    /* Post-rotate */
    {
       /* Temp pointers to make it really clear to the compiler what we're doing */
-      const kiss_fft_scalar * OPUS_RESTRICT fp = in;
+      const kiss_fft_scalar * 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 = &l->trig[0];
@@ -212,14 +214,12 @@
    int i;
    int N, N2, N4;
    kiss_twiddle_scalar sine;
-   VARDECL(kiss_fft_scalar, f);
    VARDECL(kiss_fft_scalar, f2);
    SAVE_STACK;
    N = l->n;
    N >>= shift;
    N2 = N>>1;
    N4 = N>>2;
-   ALLOC(f, N2, kiss_fft_scalar);
    ALLOC(f2, N2, kiss_fft_scalar);
    /* sin(x) ~= x here */
 #ifdef FIXED_POINT
@@ -249,81 +249,60 @@
    }
 
    /* Inverse N/4 complex FFT. This one should *not* downscale even in fixed-point */
-   opus_ifft(l->kfft[shift], (kiss_fft_cpx *)f2, (kiss_fft_cpx *)f);
+   opus_ifft(l->kfft[shift], (kiss_fft_cpx *)f2, (kiss_fft_cpx *)(out+(overlap>>1)));
 
-   /* Post-rotate */
+   /* Post-rotate and de-shuffle from both ends of the buffer at once to make
+      it in-place. */
    {
-      kiss_fft_scalar * OPUS_RESTRICT fp = f;
+      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 = &l->trig[0];
-
-      for(i=0;i<N4;i++)
+      /* 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;
-         re = fp[0];
-         im = fp[1];
+         kiss_twiddle_scalar t0, t1;
+         re = yp0[0];
+         im = yp0[1];
+         t0 = t[i<<shift];
+         t1 = t[(N4-i)<<shift];
          /* We'd scale up by 2 here, but instead it's done when mixing the windows */
-         yr = S_MUL(re,t[i<<shift]) - S_MUL(im,t[(N4-i)<<shift]);
-         yi = S_MUL(im,t[i<<shift]) + S_MUL(re,t[(N4-i)<<shift]);
+         yr = S_MUL(re,t0) - S_MUL(im,t1);
+         yi = S_MUL(im,t0) + S_MUL(re,t1);
+         re = yp1[0];
+         im = yp1[1];
          /* works because the cos is nearly one */
-         *fp++ = yr - S_MUL(yi,sine);
-         *fp++ = yi + S_MUL(yr,sine);
+         yp0[0] = -(yr - S_MUL(yi,sine));
+         yp1[1] = yi + S_MUL(yr,sine);
+
+         t0 = t[(N4-i-1)<<shift];
+         t1 = t[(i+1)<<shift];
+         /* 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(im,t0) + S_MUL(re,t1);
+         /* works because the cos is nearly one */
+         yp1[0] = -(yr - S_MUL(yi,sine));
+         yp0[1] = yi + S_MUL(yr,sine);
+         yp0 += 2;
+         yp1 -= 2;
       }
    }
-   /* De-shuffle the components for the middle of the window only */
-   {
-      const kiss_fft_scalar * OPUS_RESTRICT fp1 = f;
-      const kiss_fft_scalar * OPUS_RESTRICT fp2 = f+N2-1;
-      kiss_fft_scalar * OPUS_RESTRICT yp = f2;
-      for(i = 0; i < N4; i++)
-      {
-         *yp++ =-*fp1;
-         *yp++ = *fp2;
-         fp1 += 2;
-         fp2 -= 2;
-      }
-   }
-   out -= (N2-overlap)>>1;
+
    /* Mirror on both sides for TDAC */
    {
-      kiss_fft_scalar * OPUS_RESTRICT fp1 = f2+N4-1;
-      kiss_fft_scalar * OPUS_RESTRICT xp1 = out+N2-1;
-      kiss_fft_scalar * OPUS_RESTRICT yp1 = out+N4-overlap/2;
+      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< N4-overlap/2; i++)
+
+      for(i = 0; i < overlap/2; i++)
       {
-         *xp1 = *fp1;
-         xp1--;
-         fp1--;
-      }
-      for(; i < N4; i++)
-      {
-         kiss_fft_scalar x1;
-         x1 = *fp1--;
-         *yp1++ +=-MULT16_32_Q15(*wp1, x1);
-         *xp1-- += MULT16_32_Q15(*wp2, x1);
-         wp1++;
-         wp2--;
-      }
-   }
-   {
-      kiss_fft_scalar * OPUS_RESTRICT fp2 = f2+N4;
-      kiss_fft_scalar * OPUS_RESTRICT xp2 = out+N2;
-      kiss_fft_scalar * OPUS_RESTRICT yp2 = out+N-1-(N4-overlap/2);
-      const opus_val16 * OPUS_RESTRICT wp1 = window;
-      const opus_val16 * OPUS_RESTRICT wp2 = window+overlap-1;
-      for(i = 0; i< N4-overlap/2; i++)
-      {
-         *xp2 = *fp2;
-         xp2++;
-         fp2++;
-      }
-      for(; i < N4; i++)
-      {
-         kiss_fft_scalar x2;
-         x2 = *fp2++;
-         *yp2--  = MULT16_32_Q15(*wp1, x2);
-         *xp2++  = MULT16_32_Q15(*wp2, x2);
+         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--;
       }
diff --git a/celt/modes.c b/celt/modes.c
index ed204d7..42e68e1 100644
--- a/celt/modes.c
+++ b/celt/modes.c
@@ -345,6 +345,14 @@
    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)
diff --git a/celt/pitch.c b/celt/pitch.c
index ca0f523..0352b30 100644
--- a/celt/pitch.c
+++ b/celt/pitch.c
@@ -102,13 +102,57 @@
    }
 }
 
+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 i;
    opus_val32 ac[5];
    opus_val16 tmp=Q15ONE;
-   opus_val16 lpc[4], mem[4]={0,0,0,0};
+   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);
@@ -161,14 +205,89 @@
       tmp = MULT16_16_Q15(QCONST16(.9f,15), tmp);
       lpc[i] = MULT16_16_Q15(lpc[i], tmp);
    }
-   celt_fir(x_lp, lpc, x_lp, len>>1, 4, mem);
-
-   mem[0]=0;
-   lpc[0]=QCONST16(.8f,12);
-   celt_fir(x_lp, lpc, x_lp, len>>1, 1, mem);
-
+   /* 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);
 }
 
+#if 0 /* This is a simple version of the pitch correlation that should work
+         well on DSPs like Blackfin and TI C5x/C6x */
+
+#ifdef FIXED_POINT
+opus_val32
+#else
+void
+#endif
+celt_pitch_xcorr(opus_val16 *x, opus_val16 *y, opus_val32 *xcorr, int len, int max_pitch)
+{
+   int i, j;
+#ifdef FIXED_POINT
+   opus_val32 maxcorr=1;
+#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 */
+
+#ifdef FIXED_POINT
+opus_val32
+#else
+void
+#endif
+celt_pitch_xcorr(const opus_val16 *_x, const opus_val16 *_y, opus_val32 *xcorr, int len, int max_pitch)
+{
+   int i,j;
+#ifdef FIXED_POINT
+   opus_val32 maxcorr=1;
+#endif
+   for (i=0;i<max_pitch-3;i+=4)
+   {
+      opus_val32 sum[4]={0,0,0,0};
+      xcorr_kernel(_x, _y+i, sum, len);
+      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 = 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
+}
+
+#endif
 void pitch_search(const opus_val16 * OPUS_RESTRICT x_lp, opus_val16 * OPUS_RESTRICT y,
                   int len, int max_pitch, int *pitch)
 {
@@ -179,8 +298,8 @@
    VARDECL(opus_val16, y_lp4);
    VARDECL(opus_val32, xcorr);
 #ifdef FIXED_POINT
-   opus_val32 maxcorr=1;
-   opus_val16 xmax, ymax;
+   opus_val32 maxcorr;
+   opus_val32 xmax, ymax;
    int shift=0;
 #endif
    int offset;
@@ -204,7 +323,7 @@
 #ifdef FIXED_POINT
    xmax = celt_maxabs16(x_lp4, len>>2);
    ymax = celt_maxabs16(y_lp4, lag>>2);
-   shift = celt_ilog2(MAX16(1, MAX16(xmax, ymax)))-11;
+   shift = celt_ilog2(MAX32(1, MAX32(xmax, ymax)))-11;
    if (shift>0)
    {
       for (j=0;j<len>>2;j++)
@@ -220,16 +339,11 @@
 
    /* Coarse search with 4x decimation */
 
-   for (i=0;i<max_pitch>>2;i++)
-   {
-      opus_val32 sum = 0;
-      for (j=0;j<len>>2;j++)
-         sum = MAC16_16(sum, x_lp4[j],y_lp4[i+j]);
-      xcorr[i] = MAX32(-1, sum);
 #ifdef FIXED_POINT
-      maxcorr = MAX32(maxcorr, sum);
+   maxcorr =
 #endif
-   }
+   celt_pitch_xcorr(x_lp4, y_lp4, xcorr, len>>2, max_pitch>>2);
+
    find_best_pitch(xcorr, y_lp4, len>>2, max_pitch>>2, best_pitch
 #ifdef FIXED_POINT
                    , 0, maxcorr
@@ -287,11 +401,13 @@
    int k, i, T, T0;
    opus_val16 g, g0;
    opus_val16 pg;
-   opus_val32 xy,xx,yy;
+   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;
@@ -304,13 +420,16 @@
       *T0_=maxperiod-1;
 
    T = T0 = *T0_;
-   xx=xy=yy=0;
-   for (i=0;i<N;i++)
+   ALLOC(yy_lookup, maxperiod+1, opus_val32);
+   dual_inner_prod(x, x, x-T0, N, &xx, &xy);
+   yy_lookup[0] = xx;
+   yy=xx;
+   for (i=1;i<=maxperiod;i++)
    {
-      xy = MAC16_16(xy, x[i], x[i-T0]);
-      xx = MAC16_16(xx, x[i], x[i]);
-      yy = MAC16_16(yy, x[i-T0],x[i-T0]);
+      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;
 #ifdef FIXED_POINT
@@ -331,6 +450,7 @@
       int T1, T1b;
       opus_val16 g1;
       opus_val16 cont=0;
+      opus_val16 thresh;
       T1 = (2*T0+k)/(2*k);
       if (T1 < minperiod)
          break;
@@ -345,15 +465,9 @@
       {
          T1b = (2*second_check[k]*T0+k)/(2*k);
       }
-      xy=yy=0;
-      for (i=0;i<N;i++)
-      {
-         xy = MAC16_16(xy, x[i], x[i-T1]);
-         yy = MAC16_16(yy, x[i-T1], x[i-T1]);
-
-         xy = MAC16_16(xy, x[i], x[i-T1b]);
-         yy = MAC16_16(yy, x[i-T1b], x[i-T1b]);
-      }
+      dual_inner_prod(x, &x[-T1], &x[-T1b], N, &xy, &xy2);
+      xy += xy2;
+      yy = yy_lookup[T1] + yy_lookup[T1b];
 #ifdef FIXED_POINT
       {
          opus_val32 x2y2;
@@ -372,7 +486,14 @@
          cont = HALF32(prev_gain);
       else
          cont = 0;
-      if (g1 > QCONST16(.3f,15) + MULT16_16_Q15(QCONST16(.4f,15),g0)-cont)
+      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;
@@ -406,5 +527,6 @@
 
    if (*T0_<minperiod0)
       *T0_=minperiod0;
+   RESTORE_STACK;
    return pg;
 }
diff --git a/celt/pitch.h b/celt/pitch.h
index 2757071..caffd24 100644
--- a/celt/pitch.h
+++ b/celt/pitch.h
@@ -36,6 +36,10 @@
 
 #include "modes.h"
 
+#if defined(__SSE__) && !defined(FIXED_POINT)
+#include "x86/pitch_sse.h"
+#endif
+
 void pitch_downsample(celt_sig * OPUS_RESTRICT x[], opus_val16 * OPUS_RESTRICT x_lp,
       int len, int C);
 
@@ -45,4 +49,97 @@
 opus_val16 remove_doubling(opus_val16 *x, int maxperiod, int minperiod,
       int N, int *T0, int prev_period, opus_val16 prev_gain);
 
+/* OPT: This is the kernel you really want to optimize. It gets used a lot
+   by the prefilter and by the PLC. */
+#ifndef OVERRIDE_XCORR_KERNEL
+static inline void xcorr_kernel(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;
+   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);
+   }
+}
+#endif /* OVERRIDE_XCORR_KERNEL */
+
+#ifndef 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 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;
+}
+#endif
+
+#ifdef FIXED_POINT
+opus_val32
+#else
+void
+#endif
+celt_pitch_xcorr(const opus_val16 *_x, const opus_val16 *_y, opus_val32 *xcorr, int len, int max_pitch);
+
 #endif
diff --git a/celt/quant_bands.c b/celt/quant_bands.c
index 66f1f5f..79685e1 100644
--- a/celt/quant_bands.c
+++ b/celt/quant_bands.c
@@ -40,8 +40,8 @@
 #include "rate.h"
 
 #ifdef FIXED_POINT
-/* Mean energy in each band quantized in Q6 */
-static const signed char eMeans[25] = {
+/* 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,
@@ -49,8 +49,8 @@
        60, 60, 60, 60, 60
 };
 #else
-/* Mean energy in each band quantized in Q6 and converted back to float */
-static const opus_val16 eMeans[25] = {
+/* 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,
@@ -157,7 +157,7 @@
       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 C, int LM, int intra, opus_val16 max_decay, int lfe)
 {
    int i, c;
    int badness = 0;
@@ -222,6 +222,8 @@
             if (bits_left < 16)
                qi = IMAX(-1, qi);
          }
+         if (lfe && i>=2)
+            qi = IMIN(qi, 0);
          if (budget-tell >= 15)
          {
             int pi;
@@ -253,13 +255,13 @@
          prev[c] = prev[c] + SHL32(q,7) - MULT16_16(beta,PSHR32(q,8));
       } while (++c < C);
    }
-   return badness;
+   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 force_intra, opus_val32 *delayedIntra, int two_pass, int loss_rate, int lfe)
 {
    int intra;
    opus_val16 max_decay;
@@ -280,9 +282,6 @@
    if (tell+3 > budget)
       two_pass = intra = 0;
 
-   /* Encode the global flags using a simple probability model
-      (first symbols in the stream) */
-
    max_decay = QCONST16(16.f,DB_SHIFT);
    if (end-start>10)
    {
@@ -292,6 +291,8 @@
       max_decay = MIN32(max_decay, .125f*nbAvailableBytes);
 #endif
    }
+   if (lfe)
+      max_decay=3;
    enc_start_state = *enc;
 
    ALLOC(oldEBands_intra, C*m->nbEBands, opus_val16);
@@ -301,7 +302,7 @@
    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);
+            tell, e_prob_model[LM][1], error_intra, enc, C, LM, 1, max_decay, lfe);
    }
 
    if (!intra)
@@ -328,7 +329,7 @@
       *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);
+            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)))
       {
@@ -535,25 +536,6 @@
    }
 }
 
-void log2Amp(const CELTMode *m, int start, int end,
-      celt_ener *eBands, const opus_val16 *oldEBands, int C)
-{
-   int c, i;
-   c=0;
-   do {
-      for (i=0;i<start;i++)
-         eBands[i+c*m->nbEBands] = 0;
-      for (;i<end;i++)
-      {
-         opus_val16 lg = ADD16(oldEBands[i+c*m->nbEBands],
-                         SHL16((opus_val16)eMeans[i],6));
-         eBands[i+c*m->nbEBands] = PSHR32(celt_exp2(lg),4);
-      }
-      for (;i<m->nbEBands;i++)
-         eBands[i+c*m->nbEBands] = 0;
-   } while (++c < C);
-}
-
 void amp2Log2(const CELTMode *m, int effEnd, int end,
       celt_ener *bandE, opus_val16 *bandLogE, int C)
 {
diff --git a/celt/quant_bands.h b/celt/quant_bands.h
index bec2855..0490bca 100644
--- a/celt/quant_bands.h
+++ b/celt/quant_bands.h
@@ -35,6 +35,12 @@
 #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);
 
@@ -45,7 +51,7 @@
       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 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);
 
diff --git a/celt/rate.c b/celt/rate.c
index 4e96787..e474cf5 100644
--- a/celt/rate.c
+++ b/celt/rate.c
@@ -248,7 +248,7 @@
 static 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 *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev, int signalBandwidth)
 {
    opus_int32 psum;
    int lo, hi;
@@ -353,7 +353,7 @@
 #ifdef FUZZING
             if ((rand()&0x1) == 0)
 #else
-            if (codedBands<=start+2 || band_bits > ((j<prev?7:9)*band_width<<LM<<BITRES)>>4)
+            if (codedBands<=start+2 || (band_bits > ((j<prev?7:9)*band_width<<LM<<BITRES)>>4 && j<=signalBandwidth))
 #endif
             {
                ec_enc_bit_logp(ec, 1, 1);
@@ -524,7 +524,7 @@
 }
 
 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)
+      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;
@@ -631,7 +631,7 @@
    }
    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);
+         pulses, ebits, fine_priority, C, LM, ec, encode, prev, signalBandwidth);
    RESTORE_STACK;
    return codedBands;
 }
diff --git a/celt/rate.h b/celt/rate.h
index e0d5022..263fde9 100644
--- a/celt/rate.h
+++ b/celt/rate.h
@@ -96,6 +96,6 @@
  @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);
+      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/celt/stack_alloc.h b/celt/stack_alloc.h
index a6f06d2..1c093a8 100644
--- a/celt/stack_alloc.h
+++ b/celt/stack_alloc.h
@@ -146,4 +146,26 @@
 
 #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 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/celt/tests/test_unit_cwrs32.c b/celt/tests/test_unit_cwrs32.c
index 4695f2d..ac2a8d1 100644
--- a/celt/tests/test_unit_cwrs32.c
+++ b/celt/tests/test_unit_cwrs32.c
@@ -53,22 +53,20 @@
 
 #ifdef TEST_CUSTOM_MODES
 
-#define NDIMS (46)
+#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, 224,
- 240
+ 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,   4,
-   4
+   4,   4,   4,   4,   4,   4,   4,   4
 };
 
 #else /* TEST_CUSTOM_MODES */
@@ -97,27 +95,37 @@
     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];
-        int           y[NMAX];
-        int           sy;
-        int           yy[5];
+#endif
+        int         y[NMAX];
+        int         sy;
         opus_uint32 v;
         opus_uint32 ii;
-        int           kk;
-        int           j;
+        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){
@@ -128,7 +136,12 @@
         /*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);
@@ -139,81 +152,6 @@
            (long)v,(long)nc);
           return 2;
         }
-#ifndef SMALL_FOOTPRINT
-        if(n==2){
-          cwrsi2(k,i,yy);
-          for(j=0;j<2;j++)if(yy[j]!=y[j]){
-            fprintf(stderr,"N=2 pulse vector mismatch ({%i,%i}!={%i,%i}).\n",
-             yy[0],yy[1],y[0],y[1]);
-            return 3;
-          }
-          ii=icwrs2(yy,&kk);
-          if(ii!=i){
-            fprintf(stderr,"N=2 combination-index mismatch (%lu!=%lu).\n",
-             (long)ii,(long)i);
-            return 4;
-          }
-          if(kk!=k){
-            fprintf(stderr,"N=2 pulse count mismatch (%i,%i).\n",kk,k);
-            return 5;
-          }
-          v=ncwrs2(k);
-          if(v!=nc){
-            fprintf(stderr,"N=2 combination count mismatch (%lu,%lu).\n",
-             (long)v,(long)nc);
-            return 6;
-          }
-        }
-        else if(n==3){
-          cwrsi3(k,i,yy);
-          for(j=0;j<3;j++)if(yy[j]!=y[j]){
-            fprintf(stderr,"N=3 pulse vector mismatch "
-             "({%i,%i,%i}!={%i,%i,%i}).\n",yy[0],yy[1],yy[2],y[0],y[1],y[2]);
-            return 7;
-          }
-          ii=icwrs3(yy,&kk);
-          if(ii!=i){
-            fprintf(stderr,"N=3 combination-index mismatch (%lu!=%lu).\n",
-             (long)ii,(long)i);
-            return 8;
-          }
-          if(kk!=k){
-            fprintf(stderr,"N=3 pulse count mismatch (%i!=%i).\n",kk,k);
-            return 9;
-          }
-          v=ncwrs3(k);
-          if(v!=nc){
-            fprintf(stderr,"N=3 combination count mismatch (%lu!=%lu).\n",
-             (long)v,(long)nc);
-            return 10;
-          }
-        }
-        else if(n==4){
-          cwrsi4(k,i,yy);
-          for(j=0;j<4;j++)if(yy[j]!=y[j]){
-            fprintf(stderr,"N=4 pulse vector mismatch "
-             "({%i,%i,%i,%i}!={%i,%i,%i,%i}.\n",
-             yy[0],yy[1],yy[2],yy[3],y[0],y[1],y[2],y[3]);
-            return 11;
-          }
-          ii=icwrs4(yy,&kk);
-          if(ii!=i){
-            fprintf(stderr,"N=4 combination-index mismatch (%lu!=%lu).\n",
-             (long)ii,(long)i);
-            return 12;
-          }
-          if(kk!=k){
-            fprintf(stderr,"N=4 pulse count mismatch (%i!=%i).\n",kk,k);
-            return 13;
-          }
-          v=ncwrs4(k);
-          if(v!=nc){
-            fprintf(stderr,"N=4 combination count mismatch (%lu!=%lu).\n",
-             (long)v,(long)nc);
-            return 14;
-          }
-        }
-#endif /* SMALL_FOOTPRINT */
         /*printf(" %6u\n",i);*/
       }
       /*printf("\n");*/
diff --git a/celt/tests/test_unit_mathops.c b/celt/tests/test_unit_mathops.c
index c11f0ad..4bb780e 100644
--- a/celt/tests/test_unit_mathops.c
+++ b/celt/tests/test_unit_mathops.c
@@ -41,6 +41,8 @@
 #include "entdec.c"
 #include "entcode.c"
 #include "bands.c"
+#include "quant_bands.c"
+#include "laplace.c"
 #include "vq.c"
 #include "cwrs.c"
 #include <stdio.h>
diff --git a/celt/tests/test_unit_mdct.c b/celt/tests/test_unit_mdct.c
index f8fb9ac..ac8957f 100644
--- a/celt/tests/test_unit_mdct.c
+++ b/celt/tests/test_unit_mdct.c
@@ -151,6 +151,9 @@
        for (k=0;k<nfft;++k)
           out[k] = 0;
        clt_mdct_backward(&cfg,in,out, window, nfft/2, 0, 1);
+       /* 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, 0, 1);
@@ -180,15 +183,27 @@
         test1d(256,1);
         test1d(512,0);
         test1d(512,1);
+        test1d(1024,0);
+        test1d(1024,1);
+        test1d(2048,0);
+        test1d(2048,1);
 #ifndef RADIX_TWO_ONLY
+        test1d(36,0);
+        test1d(36,1);
         test1d(40,0);
         test1d(40,1);
+        test1d(60,0);
+        test1d(60,1);
         test1d(120,0);
         test1d(120,1);
         test1d(240,0);
         test1d(240,1);
         test1d(480,0);
         test1d(480,1);
+        test1d(960,0);
+        test1d(960,1);
+        test1d(1920,0);
+        test1d(1920,1);
 #endif
     }
     return ret;
diff --git a/celt/vq.h b/celt/vq.h
index 1ceeeeb..ffdc69c 100644
--- a/celt/vq.h
+++ b/celt/vq.h
@@ -40,11 +40,9 @@
 /** Algebraic pulse-vector quantiser. The signal x is replaced by the sum of
   * the pitch and a combination of pulses such that its norm is still equal
   * to 1. This is the function that will typically require the most CPU.
- * @param x Residual signal to quantise/encode (returns quantised version)
- * @param W Perceptual weight to use when optimising (currently unused)
+ * @param X Residual signal to quantise/encode (returns quantised version)
  * @param N Number of samples to encode
  * @param K Number of pulses to use
- * @param p Pitch vector (it is assumed that p+x is a unit vector)
  * @param enc Entropy encoder state
  * @ret A mask indicating which blocks in the band received pulses
 */
@@ -56,10 +54,9 @@
       );
 
 /** Algebraic pulse decoder
- * @param x Decoded normalised spectrum (returned)
+ * @param X Decoded normalised spectrum (returned)
  * @param N Number of samples to decode
  * @param K Number of pulses to use
- * @param p Pitch vector (automatically added to x)
  * @param dec Entropy decoder state
  * @ret A mask indicating which blocks in the band received pulses
  */
diff --git a/celt/x86/pitch_sse.h b/celt/x86/pitch_sse.h
new file mode 100644
index 0000000..63ae3d4
--- /dev/null
+++ b/celt/x86/pitch_sse.h
@@ -0,0 +1,156 @@
+/* Copyright (c) 2013 Jean-Marc Valin and John Ridges */
+/**
+   @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
+
+#include <xmmintrin.h>
+#include "arch.h"
+
+#define OVERRIDE_XCORR_KERNEL
+static inline void xcorr_kernel(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));
+}
+
+#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 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]);
+   }
+}
+
+#define OVERRIDE_COMB_FILTER_CONST
+static inline void comb_filter_const(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/celt_headers.mk b/celt_headers.mk
index f89d66a..067b294 100644
--- a/celt_headers.mk
+++ b/celt_headers.mk
@@ -2,6 +2,7 @@
 celt/arch.h \
 celt/bands.h \
 celt/celt.h \
+celt/cpu_support.h \
 include/opus_types.h \
 include/opus_defines.h \
 include/opus_custom.h \
@@ -28,4 +29,10 @@
 celt/stack_alloc.h \
 celt/vq.h \
 celt/static_modes_float.h \
-celt/static_modes_fixed.h
+celt/static_modes_fixed.h \
+celt/arm/armcpu.h \
+celt/arm/fixed_armv4.h \
+celt/arm/fixed_armv5e.h \
+celt/arm/kiss_fft_armv4.h \
+celt/arm/kiss_fft_armv5e.h \
+celt/x86/pitch_sse.h
diff --git a/celt_sources.mk b/celt_sources.mk
index 6f0a90e..e1aee8f 100644
--- a/celt_sources.mk
+++ b/celt_sources.mk
@@ -1,5 +1,7 @@
 CELT_SOURCES = celt/bands.c \
 celt/celt.c \
+celt/celt_encoder.c \
+celt/celt_decoder.c \
 celt/cwrs.c \
 celt/entcode.c \
 celt/entdec.c \
@@ -14,3 +16,6 @@
 celt/quant_bands.c \
 celt/rate.c \
 celt/vq.c
+
+CELT_SOURCES_ARM = \
+celt/arm/armcpu.c
diff --git a/configure.ac b/configure.ac
index 6394e2e..2d4896b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,67 +1,36 @@
 dnl Process this file with autoconf to produce a configure script. -*-m4-*-
 
-AC_INIT(src/opus_encoder.c)
+dnl The package_version file will be automatically synced to the git revision
+dnl by the update_version script when configured in the repository, but will
+dnl remain constant in tarball releases unless it is manually edited.
+m4_define([CURRENT_VERSION],
+          m4_esyscmd([ ./update_version 2>/dev/null || true
+                       if test -e package_version; then
+                           . ./package_version
+                           printf "$PACKAGE_VERSION"
+                       else
+                           printf "unknown"
+                       fi ]))
 
-AM_CONFIG_HEADER([config.h])
+AC_INIT([opus],[CURRENT_VERSION],[opus@xiph.org])
+
+AC_CONFIG_SRCDIR(src/opus_encoder.c)
+AC_CONFIG_MACRO_DIR([m4])
 
 dnl enable silent rules on automake 1.11 and later
 m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
 
-# Read our default version string from version.mk.
-# Please update this file for releases.
-AC_MSG_CHECKING([version.mk])
-MK_VERSION=$(awk 'BEGIN { FS = "=" }
-                  /OPUS_VERSION/ { ver = $2}
-                  END {
-                        gsub(/"/, "", ver);
-                        gsub(/^ /, "", ver);
-                        gsub(/ $/, "", ver);
-                        print ver;
-                  }' $srcdir/version.mk)
-if test -z "$MK_VERSION"; then
-  AC_MSG_RESULT([no])
-else
-  AC_MSG_RESULT([$MK_VERSION])
-  OPUS_VERSION="$MK_VERSION"
-fi
-
-# Override with the git version, if available.
-AC_MSG_CHECKING([git revision])
-GIT_VERSION=$(git describe --tags --match 'v*' 2>/dev/null | sed 's/^v//')
-if test -z "$GIT_VERSION"; then
-  AC_MSG_RESULT([no])
-else
-  AC_MSG_RESULT([$GIT_VERSION])
-  OPUS_VERSION="$GIT_VERSION"
-fi
-
-# Use 'unknown' if all else fails.
-if test -z "$OPUS_VERSION"; then
-  OPUS_VERSION="unknown"
-fi
-
-# For automake.
-PACKAGE=opus
-VERSION=$OPUS_VERSION
-
-# For autoconf
-AC_SUBST(OPUS_VERSION)
-
-# For config.h.
-AC_DEFINE_UNQUOTED([OPUS_VERSION], ["$OPUS_VERSION"],
-                   [Opus library version string])
-
 # For libtool.
 dnl Please update these for releases.
-OPUS_LT_CURRENT=3
+OPUS_LT_CURRENT=4
 OPUS_LT_REVISION=0
-OPUS_LT_AGE=3
+OPUS_LT_AGE=4
 
 AC_SUBST(OPUS_LT_CURRENT)
 AC_SUBST(OPUS_LT_REVISION)
 AC_SUBST(OPUS_LT_AGE)
 
-AM_INIT_AUTOMAKE($PACKAGE, $VERSION, no-define)
+AM_INIT_AUTOMAKE([no-define])
 AM_MAINTAINER_MODE([enable])
 
 AC_CANONICAL_HOST
@@ -73,8 +42,12 @@
 AC_C_CONST
 AC_C_INLINE
 
+AC_DEFINE([OPUS_BUILD], [], [This is a build of OPUS])
+
 #Use a hacked up version of autoconf's AC_C_RESTRICT because it's not
 #strong enough a test to detect old buggy versions of GCC (e.g. 2.95.3)
+#Note: Both this and the test for variable-size arrays below are also
+#      done by AC_PROG_CC_C99, but not thoroughly enough apparently.
 AC_CACHE_CHECK([for C/C++ restrict keyword], ac_cv_c_restrict,
   [ac_cv_c_restrict=no
    # The order here caters to the fact that C++ does not require restrict.
@@ -92,7 +65,8 @@
      test "$ac_cv_c_restrict" != no && break
    done
   ])
- AH_VERBATIM([restrict],
+
+AH_VERBATIM([restrict],
 [/* Define to the equivalent of the C99 'restrict' keyword, or to
    nothing if this is not supported.  Do not define if restrict is
    supported directly.  */
@@ -106,43 +80,74 @@
 # define _Restrict
 # define __restrict__
 #endif])
- case $ac_cv_c_restrict in
+
+case $ac_cv_c_restrict in
    restrict) ;;
    no) AC_DEFINE([restrict], []) ;;
    *)  AC_DEFINE_UNQUOTED([restrict], [$ac_cv_c_restrict]) ;;
- esac
-
-AC_DEFINE([OPUS_BUILD], [], [This is a build of OPUS])
+esac
 
 AC_MSG_CHECKING(for C99 variable-size arrays)
-AC_TRY_COMPILE( [], [static int x; char a[++x]; a[sizeof a - 1] = 0; int N; return a[0];],
-[has_var_arrays=yes;AC_DEFINE([VAR_ARRAYS], [], [Use C99 variable-size arrays])
-],
-has_var_arrays=no
-)
-AC_MSG_RESULT($has_var_arrays)
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
+                   [[static int x; char a[++x]; a[sizeof a - 1] = 0; int N; return a[0];]])],
+    [ has_var_arrays=yes
+      use_alloca="no (using var arrays)"
+      AC_DEFINE([VAR_ARRAYS], [1], [Use C99 variable-size arrays])
+    ],[
+      has_var_arrays=no
+    ])
+AC_MSG_RESULT([$has_var_arrays])
 
-AC_CHECK_HEADERS([alloca.h getopt.h])
-AC_MSG_CHECKING(for alloca)
-AC_TRY_COMPILE( [#include <alloca.h>], [
-int foo=10;
-int *array = alloca(foo);
-],
-[
-has_alloca=yes;
-if test x$has_var_arrays = "xno" ; then
-AC_DEFINE([USE_ALLOCA], [], [Make use of alloca])
-fi
-],
-has_alloca=no
-)
-AC_MSG_RESULT($has_alloca)
+AS_IF([test "$has_var_arrays" = "no"],
+  [
+   AC_CHECK_HEADERS([alloca.h])
+   AC_MSG_CHECKING(for alloca)
+   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <alloca.h>]],
+                                      [[int foo=10; int *array = alloca(foo);]])],
+     [ use_alloca=yes;
+       AC_DEFINE([USE_ALLOCA], [], [Make use of alloca])
+     ],[
+       use_alloca=no
+     ])
+   AC_MSG_RESULT([$use_alloca])
+  ])
 
-AC_CHECK_FUNC(exp,[fp_libm_not_needed=yes;LIBM=],[fp_libm_not_needed=dunno])
-if test x"$fp_libm_not_needed" = xdunno; then
-  AC_CHECK_LIB([m], [exp], [LIBS="-lm $LIBS"; LIBM="-lm"],[LIBM=])
-fi
-AC_SUBST([LIBM])
+LT_LIB_M
+
+AC_ARG_ENABLE([fixed-point],
+    [AS_HELP_STRING([--enable-fixed-point],
+                    [compile without floating point (for machines without a fast enough FPU)])],,
+    [enable_fixed_point=no])
+
+AS_IF([test "$enable_fixed_point" = "yes"],[
+  enable_float="no"
+  AC_DEFINE([FIXED_POINT], [1], [Compile as fixed-point (for machines without a fast enough FPU)])
+  PC_BUILD="fixed-point"
+],[
+  enable_float="yes";
+  PC_BUILD="floating-point"
+])
+
+AM_CONDITIONAL([FIXED_POINT], [test "$enable_fixed_point" = "yes"])
+
+AC_ARG_ENABLE([fixed-point-debug],
+    [AS_HELP_STRING([--enable-fixed-point-debug], [debug fixed-point implementation])],,
+    [enable_fixed_point_debug=no])
+
+AS_IF([test "$enable_fixed_point_debug" = "yes"],[
+  AC_DEFINE([FIXED_DEBUG], [1], [Debug fixed-point implementation])
+])
+
+AC_ARG_ENABLE([custom-modes],
+    [AS_HELP_STRING([--enable-custom-modes], [enable non-Opus modes, e.g. 44.1 kHz & 2^n frames])],,
+    [enable_custom_modes=no])
+
+AS_IF([test "$enable_custom_modes" = "yes"],[
+  AC_DEFINE([CUSTOM_MODES], [1], [Custom modes])
+  PC_BUILD="$PC_BUILD, custom modes"
+])
+
+AM_CONDITIONAL([CUSTOM_MODES], [test "$enable_custom_modes" = "yes"])
 
 has_float_approx=no
 #case "$host_cpu" in
@@ -151,173 +156,172 @@
 #  ;;
 #esac    
 
-ac_enable_fixed="no";
-ac_enable_float="yes";
-AC_ARG_ENABLE(fixed-point, [  --enable-fixed-point       compile without floating point (for machines without a fast enough FPU)],
-[if test "$enableval" = yes; then
-  ac_enable_fixed="yes";
-  ac_enable_float="no";
-  AC_DEFINE([FIXED_POINT], [1], [Compile as fixed-point (for machines without a fast enough FPU)])
-fi])
+AC_ARG_ENABLE([float-approx],
+    [AS_HELP_STRING([--enable-float-approx], [enable fast approximations for floating point])],
+    [if test "$enable_float_approx" = "yes"; then
+       AC_WARN([Floating point approximations are not supported on all platforms.])
+     fi
+    ],
+    [enable_float_approx=$has_float_approx])
 
-ac_enable_fixed_debug="no"
-AC_ARG_ENABLE(fixed-point-debug, [  --enable-fixed-point-debug debug fixed-point implementation],
-[if test "$enableval" = yes; then
-  ac_enable_fixed_debug="yes"
-  AC_DEFINE([FIXED_DEBUG], , [Debug fixed-point implementation])
-fi])
+AS_IF([test "$enable_float_approx" = "yes"],[
+  AC_DEFINE([FLOAT_APPROX], [1], [Float approximations])
+])
 
-ac_enable_custom_modes="no"
-AC_ARG_ENABLE(custom-modes, [  --enable-custom-modes      enable non-Opus modes, e.g. 44.1 kHz & 2^n frames],
-[if test "$enableval" = yes; then
-  ac_enable_custom_modes="yes"
-  AC_DEFINE([CUSTOM_MODES], , [Custom modes])
-fi])
+AC_ARG_ENABLE([asm],
+    [AS_HELP_STRING([--disable-asm], [Disable assembly optimizations])],,
+    [enable_asm=yes])
 
-float_approx=$has_float_approx
-AC_ARG_ENABLE(float-approx, [  --enable-float-approx      enable fast approximations for floating point],
-    [ if test "$enableval" = yes; then
-    AC_WARN([Floating point approximations are not supported on all platforms.])
-    float_approx=yes
-    else
-    float_approx=no
-    fi], [ float_approx=$has_float_approx ])
+rtcd_support=no
+cpu_arm=no
 
-if test "x${float_approx}" = "xyes"; then
-    AC_DEFINE([FLOAT_APPROX], , [Float approximations])
-fi
+AS_IF([test "$enable_asm" = "yes"],[
+    asm_optimization="no asm for your platform, please send patches"
+    case $host_cpu in
+    arm*)
+        cpu_arm=yes
+        AS_GCC_INLINE_ASSEMBLY([asm_optimization="ARM"],
+            [asm_optimization="disabled"])
+        if test "$asm_optimization" = "ARM" ; then
+            rtcd_support=yes
+            AC_DEFINE([ARMv4_ASM], 1, [Use generic ARMv4 asm optimizations])
+            AS_ASM_ARM_EDSP([ARMv5E_ASM=1],[ARMv5E_ASM=0])
+            if test "$ARMv5E_ASM" = "1" ; then
+                AC_DEFINE([ARMv5E_ASM], [1], [Use ARMv5E asm optimizations])
+                asm_optimization="$asm_optimization (EDSP)"
+            fi
+            AS_ASM_ARM_MEDIA([ARMv6_ASM=1],[ARMv6_ASM=0])
+            if test "$ARMv6_ASM" = "1" ; then
+                AC_DEFINE([ARMv6_ASM], [1], [Use ARMv6 asm optimizations])
+                asm_optimization="$asm_optimization (Media)"
+            fi
+            AS_ASM_ARM_NEON([ARM_HAVE_NEON=1],[ARM_HAVE_NEON=0])
+            if test "$ARM_HAVE_NEON" = "1" ; then
+              AC_DEFINE([ARM_HAVE_NEON], 1, [Use ARM NEON optimizations])
+              asm_optimization="$asm_optimization (NEON)"
+            fi
+        fi
+        ;;
+    esac
+],[
+    asm_optimization="disabled"
+])
 
-ac_enable_assertions="no"
-AC_ARG_ENABLE(assertions, [  --enable-assertions        enable additional software error checking],
-[if test "$enableval" = yes; then
-  ac_enable_assertions="yes"
-  AC_DEFINE([ENABLE_ASSERTIONS], , [Assertions])
-fi])
+AM_CONDITIONAL([CPU_ARM], [test "$cpu_arm" = "yes"])
 
-ac_enable_fuzzing="no"
-AC_ARG_ENABLE(fuzzing, [  --enable-fuzzing           causes the encoder to make random decisions],
-[if test "$enableval" = yes; then
-  ac_enable_fuzzing="yes"
-  AC_DEFINE([FUZZING], , [Fuzzing])
-fi])
+AC_ARG_ENABLE([rtcd],
+    [AS_HELP_STRING([--disable-rtcd], [Disable run-time CPU capabilities detection])],,
+    [enable_rtcd=yes])
 
-ac_enable_doc="yes"
+AS_IF([test "$enable_rtcd" = "yes"],[
+    AS_IF([test "$rtcd_support" = "yes"],[
+        AC_DEFINE([OPUS_HAVE_RTCD], [1], [Use run-time CPU capabilities detection])
+    ],[
+        rtcd_support="no rtcd for your platform, please send patches"
+    ])
+],[
+    rtcd_support="no"
+])
+
+AC_ARG_ENABLE([assertions],
+    [AS_HELP_STRING([--enable-assertions],[enable additional software error checking])],,
+    [enable_assertions=no])
+
+AS_IF([test "$enable_assertions" = "yes"], [
+  AC_DEFINE([ENABLE_ASSERTIONS], [1], [Assertions])
+])
+
+AC_ARG_ENABLE([fuzzing],
+    [AS_HELP_STRING([--enable-fuzzing],[causes the encoder to make random decisions])],,
+    [enable_fuzzing=no])
+
+AS_IF([test "$enable_fuzzing" = "yes"], [
+  AC_DEFINE([FUZZING], [1], [Fuzzing])
+])
+
 AC_ARG_ENABLE([doc],
-  AS_HELP_STRING([--disable-doc], [Do not build API documentation]),
-                 [ac_enable_doc=$enableval])
-AC_CHECK_PROG(HAVE_DOXYGEN, [doxygen], [yes], [no])
-if test "$HAVE_DOXYGEN" != "yes" -o "$ac_enable_doc" != "yes"; then
-  HAVE_DOXYGEN="false"
-  ac_enable_doc="no"
-fi
-AM_CONDITIONAL(HAVE_DOXYGEN, [test $HAVE_DOXYGEN = yes])
+    [AS_HELP_STRING([--disable-doc], [Do not build API documentation])],,
+    [enable_doc=yes])
+
+AS_IF([test "$enable_doc" = "yes"], [
+  AC_CHECK_PROG(HAVE_DOXYGEN, [doxygen], [yes], [no])
+],[
+  HAVE_DOXYGEN=no
+])
+
+AM_CONDITIONAL([HAVE_DOXYGEN], [test "$HAVE_DOXYGEN" = "yes"])
+
+AC_ARG_ENABLE([extra-programs],
+    [AS_HELP_STRING([--disable-extra-programs], [Do not build extra programs (demo and tests)])],,
+    [enable_extra_programs=yes])
+
+AM_CONDITIONAL([EXTRA_PROGRAMS], [test "$enable_extra_programs" = "yes"])
+
 
 saved_CFLAGS="$CFLAGS"
 CFLAGS="$CFLAGS -fvisibility=hidden"
 AC_MSG_CHECKING([if ${CC} supports -fvisibility=hidden])
-AC_COMPILE_IFELSE([AC_LANG_SOURCE([char foo;])],
-      [ AC_MSG_RESULT([yes])
-        SYMBOL_VISIBILITY="-fvisibility=hidden" ],
-        AC_MSG_RESULT([no]))
-CFLAGS="$saved_CFLAGS $SYMBOL_VISIBILITY"
-AC_SUBST(SYMBOL_VISIBILITY)
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char foo;]])],
+    [ AC_MSG_RESULT([yes]) ],
+    [ AC_MSG_RESULT([no])
+      CFLAGS="$saved_CFLAGS"
+    ])
 
 CFLAGS="$CFLAGS -W"
 
+warn_CFLAGS="-Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes"
 saved_CFLAGS="$CFLAGS"
-CFLAGS="$CFLAGS -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes"
-AC_MSG_CHECKING([if ${CC} supports -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes])
-AC_COMPILE_IFELSE([AC_LANG_SOURCE([char foo;])],
-      [ AC_MSG_RESULT([yes])
-        EXTRA_WARNS="-Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes" ],
-        AC_MSG_RESULT([no]))
-CFLAGS="$saved_CFLAGS $EXTRA_WARNS"
+CFLAGS="$CFLAGS $warn_CFLAGS"
+AC_MSG_CHECKING([if ${CC} supports ${warn_CFLAGS}])
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char foo;]])],
+    [ AC_MSG_RESULT([yes]) ],
+    [ AC_MSG_RESULT([no])
+      CFLAGS="$saved_CFLAGS"
+    ])
 
+saved_LIBS="$LIBS"
+LIBS="$LIBS $LIBM"
 AC_CHECK_FUNCS([lrintf])
 AC_CHECK_FUNCS([lrint])
+LIBS="$saved_LIBS"
+
 AC_CHECK_FUNCS([__malloc_hook])
 
-AC_CHECK_SIZEOF(short)
-AC_CHECK_SIZEOF(int)
-AC_CHECK_SIZEOF(long)
-AC_CHECK_SIZEOF(long long)
-
-if test x$has_char16 = "xyes" ; then
-        case 1 in
-                $ac_cv_sizeof_short) SIZE16="short";;
-                $ac_cv_sizeof_int) SIZE16="int";;
-        esac
-else
-        case 2 in
-                $ac_cv_sizeof_short) SIZE16="short";;
-                $ac_cv_sizeof_int) SIZE16="int";;
-        esac
-fi
-
-if test x$has_char16 = "xyes" ; then
-        case 2 in
-                $ac_cv_sizeof_int) SIZE32="int";;
-                $ac_cv_sizeof_long) SIZE32="long";;
-                $ac_cv_sizeof_short) SIZE32="short";;
-        esac
-else
-        case 4 in
-                $ac_cv_sizeof_int) SIZE32="int";;
-                $ac_cv_sizeof_long) SIZE32="long";;
-                $ac_cv_sizeof_short) SIZE32="short";;
-        esac
-fi
-
-AC_SUBST(SIZE16)
-AC_SUBST(SIZE32)
-
-AM_CONDITIONAL([FIXED_POINT], [test x$ac_enable_fixed = xyes])
-AM_CONDITIONAL([CUSTOM_MODES], [test x$ac_enable_custom_modes = xyes])
-
-dnl subsitutions for the pkg-config files
-if test x$ac_enable_float = xyes; then
-  PC_BUILD="floating-point"
-  PC_LIBM=$LIBM
-else
-  PC_BUILD="fixed-point"
-  PC_LIBM=
-fi
-dnl opus_custom requires libm as well
-if test x$ac_enable_custom_modes = xyes; then
-  PC_BUILD="${PC_BUILD}, custom modes"
-  PC_LIBM=$LIBM
-fi
 AC_SUBST([PC_BUILD])
-AC_SUBST([PC_LIBM])
 
 
 AC_CONFIG_FILES([Makefile opus.pc opus-uninstalled.pc
                  doc/Makefile doc/Doxyfile])
+AC_CONFIG_HEADERS([config.h])
 
 AC_OUTPUT
 
-AC_MSG_RESULT([
+AC_MSG_NOTICE([
 ------------------------------------------------------------------------
-  $PACKAGE $VERSION:  Automatic configuration OK.
-  
+  $PACKAGE_NAME $PACKAGE_VERSION:  Automatic configuration OK.
+
     Compiler support:
 
       C99 var arrays: ................ ${has_var_arrays}
       C99 lrintf: .................... ${ac_cv_func_lrintf}
-      Alloca: ........................ ${has_alloca}
+      Use alloca: .................... ${use_alloca}
     
     General configuration:
     
-      Floating point support: ........ ${ac_enable_float}
-      Fast float approximations: ..... ${float_approx}
-      Fixed point debugging: ......... ${ac_enable_fixed_debug}
-      Custom modes: .................. ${ac_enable_custom_modes}
-      Assertion checking: ............ ${ac_enable_assertions}
-      Fuzzing: ....................... ${ac_enable_fuzzing}
+      Floating point support: ........ ${enable_float}
+      Fast float approximations: ..... ${enable_float_approx}
+      Fixed point debugging: ......... ${enable_fixed_point_debug}
+      Assembly optimization: ......... ${asm_optimization}
+      Run-time CPU detection: ........ ${rtcd_support}
+      Custom modes: .................. ${enable_custom_modes}
+      Assertion checking: ............ ${enable_assertions}
+      Fuzzing: ....................... ${enable_fuzzing}
 
-      API documentation: ............. ${ac_enable_doc}
+      API documentation: ............. ${enable_doc}
+      Extra programs: ................ ${enable_extra_programs}
 ------------------------------------------------------------------------
+
+ Type "make; make install" to compile and install
+ Type "make check" to run the test suite
 ])
 
-echo "Type \"make; make install\" to compile and install";
-echo "Type \"make check\" to run the test suite";
diff --git a/doc/Doxyfile.in b/doc/Doxyfile.in
index 7f5f7dc..8a63d5e 100644
--- a/doc/Doxyfile.in
+++ b/doc/Doxyfile.in
@@ -37,7 +37,7 @@
 # for a project that appears at the top of each page and should give viewer
 # a quick idea about the purpose of the project. Keep the description short.
 
-PROJECT_BRIEF          = "IETF low-delay audio codec: API and operations manual"
+PROJECT_BRIEF          = "Opus audio codec (RFC 6716): API and operations manual"
 
 # With the PROJECT_LOGO tag one can specify an logo or icon that is
 # included in the documentation. The maximum height of the logo should not
diff --git a/doc/Makefile.am b/doc/Makefile.am
index cf5908a..02f3493 100644
--- a/doc/Makefile.am
+++ b/doc/Makefile.am
@@ -21,8 +21,8 @@
 	touch $@
 
 install-data-local:
+	$(INSTALL) -d $(DESTDIR)$(docdir)/html/search
 	for f in `find html -type f \! -name "installdox"`; do	\
-		$(INSTALL) -d $(DESTDIR)$(docdir)/html/search;	\
 		$(INSTALL_DATA) $$f $(DESTDIR)$(docdir)/$$f;	\
 	done
 
diff --git a/doc/build_draft.sh b/doc/build_draft.sh
new file mode 100755
index 0000000..d15b22a
--- /dev/null
+++ b/doc/build_draft.sh
@@ -0,0 +1,104 @@
+#!/bin/sh
+
+# Copyright (c) 2011-2012 Xiph.Org Foundation and Mozilla Corporation
+#
+#  This file is extracted from RFC6716. Please see that RFC for additional
+#  information.
+#
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions
+#  are met:
+#
+#  - Redistributions of source code must retain the above copyright
+#  notice, this list of conditions and the following disclaimer.
+#
+#  - Redistributions in binary form must reproduce the above copyright
+#  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.
+
+#Stop on errors
+set -e
+#Set the CWD to the location of this script
+[ -n "${0%/*}" ] && cd "${0%/*}"
+
+toplevel=".."
+destdir="opus_source"
+
+echo packaging source code
+rm -rf "${destdir}"
+mkdir "${destdir}"
+mkdir "${destdir}/src"
+mkdir "${destdir}/silk"
+mkdir "${destdir}/silk/float"
+mkdir "${destdir}/silk/fixed"
+mkdir "${destdir}/celt"
+mkdir "${destdir}/include"
+for f in `cat "${toplevel}"/opus_sources.mk "${toplevel}"/celt_sources.mk \
+ "${toplevel}"/silk_sources.mk "${toplevel}"/opus_headers.mk \
+ "${toplevel}"/celt_headers.mk "${toplevel}"/silk_headers.mk \
+ | grep '\.[ch]' | sed -e 's/^.*=//' -e 's/\\\\//'` ; do
+  cp -a "${toplevel}/${f}" "${destdir}/${f}"
+done
+cp -a "${toplevel}"/src/opus_demo.c "${destdir}"/src/
+cp -a "${toplevel}"/src/opus_compare.c "${destdir}"/src/
+cp -a "${toplevel}"/celt/opus_custom_demo.c "${destdir}"/celt/
+cp -a "${toplevel}"/Makefile.unix "${destdir}"/Makefile
+cp -a "${toplevel}"/opus_sources.mk "${destdir}"/
+cp -a "${toplevel}"/celt_sources.mk "${destdir}"/
+cp -a "${toplevel}"/silk_sources.mk "${destdir}"/
+cp -a "${toplevel}"/README.draft "${destdir}"/README
+cp -a "${toplevel}"/COPYING "${destdir}"/COPYING
+cp -a "${toplevel}"/tests/run_vectors.sh "${destdir}"/
+
+GZIP=-9 tar --owner=root --group=root --format=v7 -czf opus_source.tar.gz "${destdir}"
+echo building base64 version
+cat opus_source.tar.gz| base64 | tr -d '\n' | fold -w 64 | \
+ sed -e 's/^/\<spanx style="vbare"\>###/' -e 's/$/\<\/spanx\>\<vspace\/\>/' > \
+ opus_source.base64
+
+
+#echo '<figure>' > opus_compare_escaped.c
+#echo '<artwork>' >> opus_compare_escaped.c
+#echo '<![CDATA[' >> opus_compare_escaped.c
+#cat opus_compare.c >> opus_compare_escaped.c
+#echo ']]>' >> opus_compare_escaped.c
+#echo '</artwork>' >> opus_compare_escaped.c
+#echo '</figure>' >> opus_compare_escaped.c
+
+if [[ ! -d ../opus_testvectors ]] ; then
+  echo "Downloading test vectors..."
+  wget 'http://opus-codec.org/testvectors/opus_testvectors.tar.gz'
+  tar -C .. -xvzf opus_testvectors.tar.gz
+fi
+echo '<figure>' > testvectors_sha1
+echo '<artwork>' >> testvectors_sha1
+echo '<![CDATA[' >> testvectors_sha1
+(cd ../opus_testvectors; sha1sum *.bit *.dec) >> testvectors_sha1
+#cd opus_testvectors
+#sha1sum *.bit *.dec >> ../testvectors_sha1
+#cd ..
+echo ']]>' >> testvectors_sha1
+echo '</artwork>' >> testvectors_sha1
+echo '</figure>' >> testvectors_sha1
+
+echo running xml2rfc
+xml2rfc draft-ietf-codec-opus.xml draft-ietf-codec-opus.html &
+xml2rfc draft-ietf-codec-opus.xml
+wait
diff --git a/doc/build_oggdraft.sh b/doc/build_oggdraft.sh
new file mode 100755
index 0000000..30ee534
--- /dev/null
+++ b/doc/build_oggdraft.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+
+# Copyright (c) 2012 Xiph.Org Foundation and Mozilla Corporation
+#
+#  This file is extracted from RFC6716. Please see that RFC for additional
+#  information.
+#
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions
+#  are met:
+#
+#  - Redistributions of source code must retain the above copyright
+#  notice, this list of conditions and the following disclaimer.
+#
+#  - Redistributions in binary form must reproduce the above copyright
+#  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.
+
+#Stop on errors
+set -e
+#Set the CWD to the location of this script
+[ -n "${0%/*}" ] && cd "${0%/*}"
+
+if test -z `which xml2rfc 2> /dev/null`; then
+  echo "Error: couldn't find xml2rfc."
+  echo
+  echo "Please install xml2rfc version 2 or later."
+  echo "E.g. 'pip install xml2rfc' or follow the instructions"
+  echo "on http://pypi.python.org/pypi/xml2rfc/ or tools.ietf.org."
+  exit 1
+fi
+
+echo running xml2rfc
+# version 2 syntax
+xml2rfc draft-ietf-codec-oggopus.xml --text --html
diff --git a/doc/draft-ietf-codec-oggopus.xml b/doc/draft-ietf-codec-oggopus.xml
new file mode 100644
index 0000000..6131e69
--- /dev/null
+++ b/doc/draft-ietf-codec-oggopus.xml
@@ -0,0 +1,1447 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE rfc SYSTEM 'rfc2629.dtd' [
+<!ENTITY rfc2119 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.2119.xml'>
+<!ENTITY rfc3533 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.3533.xml'>
+<!ENTITY rfc3629 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.3629.xml'>
+<!ENTITY rfc4732 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.4732.xml'>
+<!ENTITY rfc5334 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.5334.xml'>
+<!ENTITY rfc6381 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.6381.xml'>
+<!ENTITY rfc6716 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.6716.xml'>
+]>
+<?rfc toc="yes" symrefs="yes" ?>
+
+<rfc ipr="trust200902" category="std" docName="draft-ietf-codec-oggopus-01">
+
+<front>
+<title abbrev="Ogg Opus">Ogg Encapsulation for the Opus Audio Codec</title>
+<author initials="T.B." surname="Terriberry" fullname="Timothy B. Terriberry">
+<organization>Mozilla Corporation</organization>
+<address>
+<postal>
+<street>650 Castro Street</street>
+<city>Mountain View</city>
+<region>CA</region>
+<code>94041</code>
+<country>USA</country>
+</postal>
+<phone>+1 650 903-0800</phone>
+<email>tterribe@xiph.org</email>
+</address>
+</author>
+
+<author initials="R." surname="Lee" fullname="Ron Lee">
+<organization>Voicetronix</organization>
+<address>
+<postal>
+<street>246 Pulteney Street, Level 1</street>
+<city>Adelaide</city>
+<region>SA</region>
+<code>5000</code>
+<country>Australia</country>
+</postal>
+<phone>+61 8 8232 9112</phone>
+<email>ron@debian.org</email>
+</address>
+</author>
+
+<author initials="R." surname="Giles" fullname="Ralph Giles">
+<organization>Mozilla Corporation</organization>
+<address>
+<postal>
+<street>163 West Hastings Street</street>
+<city>Vancouver</city>
+<region>BC</region>
+<code>V6B 1H5</code>
+<country>Canada</country>
+</postal>
+<phone>+1 604 778 1540</phone>
+<email>giles@xiph.org</email>
+</address>
+</author>
+
+<date day="24" month="May" year="2013"/>
+<area>RAI</area>
+<workgroup>codec</workgroup>
+
+<abstract>
+<t>
+This document defines the Ogg encapsulation for the Opus interactive speech and
+ audio codec.
+This allows data encoded in the Opus format to be stored in an Ogg logical
+ bitstream.
+Ogg encapsulation provides Opus with a long-term storage format supporting
+ all of the essential features, including metadata, fast and accurate seeking,
+ corruption detection, recapture after errors, low overhead, and the ability to
+ multiplex Opus with other codecs (including video) with minimal buffering.
+It also provides a live streamable format, capable of delivery over a reliable
+ stream-oriented transport, without requiring all the data, or even the total
+ length of the data, up-front, in a form that is identical to the on-disk
+ storage format.
+</t>
+</abstract>
+</front>
+
+<middle>
+<section anchor="intro" title="Introduction">
+<t>
+The IETF Opus codec is a low-latency audio codec optimized for both voice and
+ general-purpose audio.
+See <xref target="RFC6716"/> for technical details.
+This document defines the encapsulation of Opus in a continuous, logical Ogg
+ bitstream&nbsp;<xref target="RFC3533"/>.
+</t>
+<t>
+Ogg bitstreams are made up of a series of 'pages', each of which contains data
+ from one or more 'packets'.
+Pages are the fundamental unit of multiplexing in an Ogg stream.
+Each page is associated with a particular logical stream and contains a capture
+ pattern and checksum, flags to mark the beginning and end of the logical
+ stream, and a 'granule position' that represents an absolute position in the
+ stream, to aid seeking.
+A single page can contain up to 65,025 octets of packet data from up to 255
+ different packets.
+Packets may be split arbitrarily across pages, and continued from one page to
+ the next (allowing packets much larger than would fit on a single page).
+Each page contains 'lacing values' that indicate how the data is partitioned
+ into packets, allowing a demuxer to recover the packet boundaries without
+ examining the encoded data.
+A packet is said to 'complete' on a page when the page contains the final
+ lacing value corresponding to that packet.
+</t>
+<t>
+This encapsulation defines the required contents of the packet data, including
+ the necessary headers, the organization of those packets into a logical
+ stream, and the interpretation of the codec-specific granule position field.
+It does not attempt to describe or specify the existing Ogg container format.
+Readers unfamiliar with the basic concepts mentioned above are encouraged to
+ review the details in <xref target="RFC3533"/>.
+</t>
+
+</section>
+
+<section anchor="terminology" title="Terminology">
+<t>
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
+ "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
+ interpreted as described in <xref target="RFC2119"/>.
+</t>
+
+<t>
+Implementations that fail to satisfy one or more "MUST" requirements are
+ considered non-compliant.
+Implementations that satisfy all "MUST" requirements, but fail to satisfy one
+ or more "SHOULD" requirements are said to be "conditionally compliant".
+All other implementations are "unconditionally compliant".
+</t>
+
+</section>
+
+<section anchor="packet_organization" title="Packet Organization">
+<t>
+An Opus stream is organized as follows.
+</t>
+<t>
+There are two mandatory header packets.
+The granule position of the pages on which these packets complete MUST be zero.
+</t>
+<t>
+The first packet in the logical Ogg bitstream MUST contain the identification
+ (ID) header, which uniquely identifies a stream as Opus audio.
+The format of this header is defined in <xref target="id_header"/>.
+It MUST be placed alone (without any other packet data) on the first page of
+ the logical Ogg bitstream, and must complete on that page.
+This page MUST have its 'beginning of stream' flag set.
+</t>
+<t>
+The second packet in the logical Ogg bitstream MUST contain the comment header,
+ which contains user-supplied metadata.
+The format of this header is defined in <xref target="comment_header"/>.
+It MAY span one or more pages, beginning on the second page of the logical
+ stream.
+However many pages it spans, the comment header packet MUST finish the page on
+ which it completes.
+</t>
+<t>
+All subsequent pages are audio data pages, and the Ogg packets they contain are
+ audio data packets.
+Each audio data packet contains one Opus packet for each of N different
+ streams, where N is typically one for mono or stereo, but may be greater than
+ one for, e.g., multichannel audio.
+The value N is specified in the ID header (see
+ <xref target="channel_mapping"/>), and is fixed over the entire length of the
+ logical Ogg bitstream.
+</t>
+<t>
+The first N-1 Opus packets, if any, are packed one after another into the Ogg
+ packet, using the self-delimiting framing from Appendix&nbsp;B of
+ <xref target="RFC6716"/>.
+The remaining Opus packet is packed at the end of the Ogg packet using the
+ regular, undelimited framing from Section&nbsp;3 of <xref target="RFC6716"/>.
+All of the Opus packets in a single Ogg packet MUST be constrained to have the
+ same duration.
+The duration and coding modes of each Opus packet are contained in the
+ TOC (table of contents) sequence in the first few bytes.
+A decoder SHOULD treat any Opus packet whose duration is different from that of
+ the first Opus packet in an Ogg packet as if it were an Opus packet with an
+ illegal TOC sequence.
+</t>
+<t>
+The first audio data page SHOULD NOT have the 'continued packet' flag set
+ (which would indicate the first audio data packet is continued from a previous
+ page).
+Packets MUST be placed into Ogg pages in order until the end of stream.
+Audio packets MAY span page boundaries.
+A decoder MUST treat a zero-octet audio data packet as if it were an Opus
+ packet with an illegal TOC sequence.
+The last page SHOULD have the 'end of stream' flag set, but implementations
+ should be prepared to deal with truncated streams that do not have a page
+ marked 'end of stream'.
+The final packet on the last page SHOULD NOT be a continued packet, i.e., the
+ final lacing value should be less than 255.
+There MUST NOT be any more pages in an Opus logical bitstream after a page
+ marked 'end of stream'.
+</t>
+</section>
+
+<section anchor="granpos" title="Granule Position">
+<t>
+The granule position of an audio data page encodes the total number of PCM
+ samples in the stream up to and including the last fully-decodable sample from
+ the last packet completed on that page.
+A page that is entirely spanned by a single packet (that completes on a
+ subsequent page) has no granule position, and the granule position field MUST
+ be set to the special value '-1' in two's complement.
+</t>
+
+<t>
+The granule position of an audio data page is in units of PCM audio samples at
+ a fixed rate of 48&nbsp;kHz (per channel; a stereo stream's granule position
+ does not increment at twice the speed of a mono stream).
+It is possible to run an Opus decoder at other sampling rates, but the value
+ in the granule position field always counts samples assuming a 48&nbsp;kHz
+ decoding rate, and the rest of this specification makes the same assumption.
+</t>
+
+<t>
+The duration of an Opus packet may be any multiple of 2.5&nbsp;ms, up to a
+ maximum of 120&nbsp;ms.
+This duration is encoded in the TOC sequence at the beginning of each packet.
+The number of samples returned by a decoder corresponds to this duration
+ exactly, even for the first few packets.
+For example, a 20&nbsp;ms packet fed to a decoder running at 48&nbsp;kHz will
+ always return 960&nbsp;samples.
+A demuxer can parse the TOC sequence at the beginning of each Ogg packet to
+ work backwards or forwards from a packet with a known granule position (i.e.,
+ the last packet completed on some page) in order to assign granule positions
+ to every packet, or even every individual sample.
+The one exception is the last page in the stream, as described below.
+</t>
+
+<t>
+All other pages with completed packets after the first MUST have a granule
+ position equal to the number of samples contained in packets that complete on
+ that page plus the granule position of the most recent page with completed
+ packets.
+This guarantees that a demuxer can assign individual packets the same granule
+ position when working forwards as when working backwards.
+For this to work, there cannot be any gaps.
+In order to support capturing a stream that uses discontinuous transmission
+ (DTX), an encoder SHOULD emit packets that explicitly request the use of
+ Packet Loss Concealment (PLC) (i.e., with a frame length of 0, as defined in
+ Section 3.2.1 of <xref target="RFC6716"/>) in place of the packets that were
+ not transmitted.
+</t>
+
+<section anchor="preskip" title="Pre-skip">
+<t>
+There is some amount of latency introduced during the decoding process, to
+ allow for overlap in the MDCT modes, stereo mixing in the LP modes, and
+ resampling, and the encoder will introduce even more latency (though the exact
+ amount is not specified).
+Therefore, the first few samples produced by the decoder do not correspond to
+ real input audio, but are instead composed of padding inserted by the encoder
+ to compensate for this latency.
+These samples need to be stored and decoded, as Opus is an asymptotically
+ convergent predictive codec, meaning the decoded contents of each frame depend
+ on the recent history of decoder inputs.
+However, a decoder will want to skip these samples after decoding them.
+</t>
+
+<t>
+A 'pre-skip' field in the ID header (see <xref target="id_header"/>) signals
+ the number of samples which SHOULD be skipped (decoded but discarded) at the
+ beginning of the stream.
+This provides sufficient history to the decoder so that it has already
+ converged before the stream's output begins.
+It may also be used to perform sample-accurate cropping of existing encoded
+ streams.
+This amount need not be a multiple of 2.5&nbsp;ms, may be smaller than a single
+ packet, or may span the contents of several packets.
+</t>
+</section>
+
+<section anchor="pcm_sample_position" title="PCM Sample Position">
+<t>
+The PCM sample position is determined from the granule position using the
+ formula
+<figure align="center">
+<artwork align="center"><![CDATA[
+'PCM sample position' = 'granule position' - 'pre-skip' .
+]]></artwork>
+</figure>
+</t>
+
+<t>
+For example, if the granule position of the first audio data page is 59,971,
+ and the pre-skip is 11,971, then the PCM sample position of the last decoded
+ sample from that page is 48,000.
+This can be converted into a playback time using the formula
+<figure align="center">
+<artwork align="center"><![CDATA[
+                  'PCM sample position'
+'playback time' = --------------------- .
+                         48000.0
+]]></artwork>
+</figure>
+</t>
+
+<t>
+The initial PCM sample position before any samples are played is normally '0'.
+In this case, the PCM sample position of the first audio sample to be played
+ starts at '1', because it marks the time on the clock
+ <spanx style="emph">after</spanx> that sample has been played, and a stream
+ that is exactly one second long has a final PCM sample position of '48000',
+ as in the example here.
+</t>
+
+<t>
+Vorbis streams use a granule position smaller than the number of audio samples
+ contained in the first audio data page to indicate that some of those samples
+ must be trimmed from the output (see <xref target="vorbis-trim"/>).
+However, to do so, Vorbis requires that the first audio data page contains
+ exactly two packets, in order to allow the decoder to perform PCM position
+ adjustments before needing to return any PCM data.
+Opus uses the pre-skip mechanism for this purpose instead, since the encoder
+ may introduce more than a single packet's worth of latency, and since very
+ large packets in streams with a very large number of channels might not fit
+ on a single page.
+</t>
+</section>
+
+<section anchor="end_trimming" title="End Trimming">
+<t>
+The page with the 'end of stream' flag set MAY have a granule position that
+ indicates the page contains less audio data than would normally be returned by
+ decoding up through the final packet.
+This is used to end the stream somewhere other than an even frame boundary.
+The granule position of the most recent audio data page with completed packets
+ is used to make this determination, or '0' is used if there were no previous
+ audio data pages with a completed packet.
+The difference between these granule positions indicates how many samples to
+ keep after decoding the packets that completed on the final page.
+The remaining samples are discarded.
+The number of discarded samples SHOULD be no larger than the number decoded
+ from the last packet.
+</t>
+</section>
+
+<section anchor="start_granpos_restrictions"
+ title="Restrictions on the Initial Granule Position">
+<t>
+The granule position of the first audio data page with a completed packet MAY
+ be larger than the number of samples contained in packets that complete on
+ that page, however it MUST NOT be smaller, unless that page has the 'end of
+ stream' flag set.
+Allowing a granule position larger than the number of samples allows the
+ beginning of a stream to be cropped or a live stream to be joined without
+ rewriting the granule position of all the remaining pages.
+This means that the PCM sample position just before the first sample to be
+ played may be larger than '0'.
+Synchronization when multiplexing with other logical streams still uses the PCM
+ sample position relative to '0' to compute sample times.
+This does not affect the behavior of pre-skip: exactly 'pre-skip' samples
+ should be skipped from the beginning of the decoded output, even if the
+ initial PCM sample position is greater than zero.
+</t>
+
+<t>
+On the other hand, a granule position that is smaller than the number of
+ decoded samples prevents a demuxer from working backwards to assign each
+ packet or each individual sample a valid granule position, since granule
+ positions must be non-negative.
+A decoder MUST reject as invalid any stream where the granule position is
+ smaller than the number of samples contained in packets that complete on the
+ first audio data page with a completed packet, unless that page has the 'end
+ of stream' flag set.
+It MAY defer this action until it decodes the last packet completed on that
+ page.
+</t>
+
+<t>
+If that page has the 'end of stream' flag set, a demuxer MUST reject as invalid
+ any stream where its granule position is smaller than the 'pre-skip' amount.
+This would indicate that more samples should be skipped from the initial
+ decoded output than exist in the stream.
+If the granule position is smaller than the number of decoded samples produced
+ by the packets that complete on that page, then a demuxer MUST use an initial
+ granule position of '0', and can work forwards from '0' to timestamp
+ individual packets.
+If the granule position is larger than the number of decoded samples available,
+ then the demuxer MUST still work backwards as described above, even if the
+ 'end of stream' flag is set, to determine the initial granule position, and
+ thus the initial PCM sample position.
+Both of these will be greater than '0' in this case.
+</t>
+</section>
+
+<section anchor="seeking_and_preroll" title="Seeking and Pre-roll">
+<t>
+Seeking in Ogg files is best performed using a bisection search for a page
+ whose granule position corresponds to a PCM position at or before the seek
+ target.
+With appropriately weighted bisection, accurate seeking can be performed with
+ just three or four bisections even in multi-gigabyte files.
+See <xref target="seeking"/> for general implementation guidance.
+</t>
+
+<t>
+When seeking within an Ogg Opus stream, the decoder SHOULD start decoding (and
+ discarding the output) at least 3840&nbsp;samples (80&nbsp;ms) prior to the
+ seek target in order to ensure that the output audio is correct by the time it
+ reaches the seek target.
+This 'pre-roll' is separate from, and unrelated to, the 'pre-skip' used at the
+ beginning of the stream.
+If the point 80&nbsp;ms prior to the seek target comes before the initial PCM
+ sample position, the decoder SHOULD start decoding from the beginning of the
+ stream, applying pre-skip as normal, regardless of whether the pre-skip is
+ larger or smaller than 80&nbsp;ms, and then continue to discard the samples
+ required to reach the seek target (if any).
+</t>
+</section>
+
+</section>
+
+<section anchor="headers" title="Header Packets">
+<t>
+An Opus stream contains exactly two mandatory header packets:
+ an identification header and a comment header.
+</t>
+
+<section anchor="id_header" title="Identification Header">
+
+<figure anchor="id_header_packet" title="ID Header Packet" align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|      'O'      |      'p'      |      'u'      |      's'      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|      'H'      |      'e'      |      'a'      |      'd'      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|  Version = 1  | Channel Count |           Pre-skip            |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                     Input Sample Rate (Hz)                    |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|   Output Gain (Q7.8 in dB)    | Mapping Family|               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+               :
+|                                                               |
+:               Optional Channel Mapping Table...               :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+The fields in the identification (ID) header have the following meaning:
+<list style="numbers">
+<t><spanx style="strong">Magic Signature</spanx>:
+<vspace blankLines="1"/>
+This is an 8-octet (64-bit) field that allows codec identification and is
+ human-readable.
+It contains, in order, the magic numbers:
+<list style="empty">
+<t>0x4F 'O'</t>
+<t>0x70 'p'</t>
+<t>0x75 'u'</t>
+<t>0x73 's'</t>
+<t>0x48 'H'</t>
+<t>0x65 'e'</t>
+<t>0x61 'a'</t>
+<t>0x64 'd'</t>
+</list>
+Starting with "Op" helps distinguish it from audio data packets, as this is an
+ invalid TOC sequence.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Version</spanx> (8 bits, unsigned):
+<vspace blankLines="1"/>
+The version number MUST always be '1' for this version of the encapsulation
+ specification.
+Implementations SHOULD treat streams where the upper four bits of the version
+ number match that of a recognized specification as backwards-compatible with
+ that specification.
+That is, the version number can be split into "major" and "minor" version
+ sub-fields, with changes to the "minor" sub-field (in the lower four bits)
+ signaling compatible changes.
+For example, a decoder implementing this specification SHOULD accept any stream
+ with a version number of '15' or less, and SHOULD assume any stream with a
+ version number '16' or greater is incompatible.
+The initial version '1' was chosen to keep implementations from relying on this
+ octet as a null terminator for the "OpusHead" string.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Output Channel Count</spanx> 'C' (8 bits, unsigned):
+<vspace blankLines="1"/>
+This is the number of output channels.
+This might be different than the number of encoded channels, which can change
+ on a packet-by-packet basis.
+This value MUST NOT be zero.
+The maximum allowable value depends on the channel mapping family, and might be
+ as large as 255.
+See <xref target="channel_mapping"/> for details.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Pre-skip</spanx> (16 bits, unsigned, little
+ endian):
+<vspace blankLines="1"/>
+This is the number of samples (at 48&nbsp;kHz) to discard from the decoder
+ output when starting playback, and also the number to subtract from a page's
+ granule position to calculate its PCM sample position.
+When cropping the beginning of existing Ogg Opus streams, a pre-skip of at
+ least 3,840&nbsp;samples (80&nbsp;ms) is RECOMMENDED to ensure complete
+ convergence in the decoder.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Input Sample Rate</spanx> (32 bits, unsigned, little
+ endian):
+<vspace blankLines="1"/>
+This field is <spanx style="emph">not</spanx> the sample rate to use for
+ playback of the encoded data.
+<vspace blankLines="1"/>
+Opus has a handful of coding modes, with internal audio bandwidths of 4, 6, 8,
+ 12, and 20&nbsp;kHz.
+Each packet in the stream may have a different audio bandwidth.
+Regardless of the audio bandwidth, the reference decoder supports decoding any
+ stream at a sample rate of 8, 12, 16, 24, or 48&nbsp;kHz.
+The original sample rate of the encoder input is not preserved by the lossy
+ compression.
+<vspace blankLines="1"/>
+An Ogg Opus player SHOULD select the playback sample rate according to the
+ following procedure:
+<list style="numbers">
+<t>If the hardware supports 48&nbsp;kHz playback, decode at 48&nbsp;kHz.</t>
+<t>Otherwise, if the hardware's highest available sample rate is a supported
+ rate, decode at this sample rate.</t>
+<t>Otherwise, if the hardware's highest available sample rate is less than
+ 48&nbsp;kHz, decode at the highest supported rate above this and resample.</t>
+<t>Otherwise, decode at 48&nbsp;kHz and resample.</t>
+</list>
+However, the 'Input Sample Rate' field allows the encoder to pass the sample
+ rate of the original input stream as metadata.
+This may be useful when the user requires the output sample rate to match the
+ input sample rate.
+For example, a non-player decoder writing PCM format samples to disk might
+ choose to resample the output audio back to the original input sample rate to
+ reduce surprise to the user, who might reasonably expect to get back a file
+ with the same sample rate as the one they fed to the encoder.
+<vspace blankLines="1"/>
+A value of zero indicates 'unspecified'.
+Encoders SHOULD write the actual input sample rate or zero, but decoder
+ implementations which do something with this field SHOULD take care to behave
+ sanely if given crazy values (e.g., do not actually upsample the output to
+ 10 MHz if requested).
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Output Gain</spanx> (16 bits, signed, little
+ endian):
+<vspace blankLines="1"/>
+This is a gain to be applied by the decoder.
+It is 20*log10 of the factor to scale the decoder output by to achieve the
+ desired playback volume, stored in a 16-bit, signed, two's complement
+ fixed-point value with 8 fractional bits (i.e., Q7.8).
+To apply the gain, a decoder could use
+<figure align="center">
+<artwork align="center"><![CDATA[
+sample *= pow(10, output_gain/(20.0*256)) ,
+]]></artwork>
+</figure>
+ where output_gain is the raw 16-bit value from the header.
+<vspace blankLines="1"/>
+Virtually all players and media frameworks should apply it by default.
+If a player chooses to apply any volume adjustment or gain modification, such
+ as the R128_TRACK_GAIN (see <xref target="comment_header"/>) or a user-facing
+ volume knob, the adjustment MUST be applied in addition to this output gain in
+ order to achieve playback at the desired volume.
+<vspace blankLines="1"/>
+An encoder SHOULD set this field to zero, and instead apply any gain prior to
+ encoding, when this is possible and does not conflict with the user's wishes.
+The output gain should only be nonzero when the gain is adjusted after
+ encoding, or when the user wishes to adjust the gain for playback while
+ preserving the ability to recover the original signal amplitude.
+<vspace blankLines="1"/>
+Although the output gain has enormous range (+/- 128 dB, enough to amplify
+ inaudible sounds to the threshold of physical pain), most applications can
+ only reasonably use a small portion of this range around zero.
+The large range serves in part to ensure that gain can always be losslessly
+ transferred between OpusHead and R128_TRACK_GAIN (see below) without
+ saturating.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Channel Mapping Family</spanx> (8 bits,
+ unsigned):
+<vspace blankLines="1"/>
+This octet indicates the order and semantic meaning of the various channels
+ encoded in each Ogg packet.
+<vspace blankLines="1"/>
+Each possible value of this octet indicates a mapping family, which defines a
+ set of allowed channel counts, and the ordered set of channel names for each
+ allowed channel count.
+The details are described in <xref target="channel_mapping"/>.
+</t>
+<t><spanx style="strong">Channel Mapping Table</spanx>:
+This table defines the mapping from encoded streams to output channels.
+It is omitted when the channel mapping family is 0, but REQUIRED otherwise.
+Its contents are specified in <xref target="channel_mapping"/>.
+</t>
+</list>
+</t>
+
+<t>
+All fields in the ID headers are REQUIRED, except for the channel mapping
+ table, which is omitted when the channel mapping family is 0.
+Implementations SHOULD reject ID headers which do not contain enough data for
+ these fields, even if they contain a valid Magic Signature.
+Future versions of this specification, even backwards-compatible versions,
+ might include additional fields in the ID header.
+If an ID header has a compatible major version, but a larger minor version,
+ an implementation MUST NOT reject it for containing additional data not
+ specified here.
+However, implementations MAY reject streams in which the ID header does not
+ complete on the first page.
+</t>
+
+<section anchor="channel_mapping" title="Channel Mapping">
+<t>
+An Ogg Opus stream allows mapping one number of Opus streams (N) to a possibly
+ larger number of decoded channels (M+N) to yet another number of output
+ channels (C), which might be larger or smaller than the number of decoded
+ channels.
+The order and meaning of these channels are defined by a channel mapping,
+ which consists of the 'channel mapping family' octet and, for channel mapping
+ families other than family&nbsp;0, a channel mapping table, as illustrated in
+ <xref target="channel_mapping_table"/>.
+</t>
+
+<figure anchor="channel_mapping_table" title="Channel Mapping Table"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+                                                +-+-+-+-+-+-+-+-+
+                                                | Stream Count  |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| Coupled Count |              Channel Mapping...               :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+The fields in the channel mapping table have the following meaning:
+<list style="numbers" counter="8">
+<t><spanx style="strong">Stream Count</spanx> 'N' (8 bits, unsigned):
+<vspace blankLines="1"/>
+This is the total number of streams encoded in each Ogg packet.
+This value is required to correctly parse the packed Opus packets inside an
+ Ogg packet, as described in <xref target="packet_organization"/>.
+This value MUST NOT be zero, as without at least one Opus packet with a valid
+ TOC sequence, a demuxer cannot recover the duration of an Ogg packet.
+<vspace blankLines="1"/>
+For channel mapping family&nbsp;0, this value defaults to 1, and is not coded.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Coupled Stream Count</spanx> 'M' (8 bits, unsigned):
+This is the number of streams whose decoders should be configured to produce
+ two channels.
+This MUST be no larger than the total number of streams, N.
+<vspace blankLines="1"/>
+Each packet in an Opus stream has an internal channel count of 1 or 2, which
+ can change from packet to packet.
+This is selected by the encoder depending on the bitrate and the audio being
+ encoded.
+The original channel count of the encoder input is not preserved by the lossy
+ compression.
+<vspace blankLines="1"/>
+Regardless of the internal channel count, any Opus stream can be decoded as
+ mono (a single channel) or stereo (two channels) by appropriate initialization
+ of the decoder.
+The 'coupled stream count' field indicates that the first M Opus decoders are
+ to be initialized in stereo mode, and the remaining N-M decoders are to be
+ initialized in mono mode.
+The total number of decoded channels, (M+N), MUST be no larger than 255, as
+ there is no way to index more channels than that in the channel mapping.
+<vspace blankLines="1"/>
+For channel mapping family&nbsp;0, this value defaults to C-1 (i.e., 0 for mono
+ and 1 for stereo), and is not coded.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Channel Mapping</spanx> (8*C bits):
+This contains one octet per output channel, indicating which decoded channel
+ should be used for each one.
+Let 'index' be the value of this octet for a particular output channel.
+This value MUST either be smaller than (M+N), or be the special value 255.
+If 'index' is less than 2*M, the output MUST be taken from decoding stream
+ ('index'/2) as stereo and selecting the left channel if 'index' is even, and
+ the right channel if 'index' is odd.
+If 'index' is 2*M or larger, the output MUST be taken from decoding stream
+ ('index'-M) as mono.
+If 'index' is 255, the corresponding output channel MUST contain pure silence.
+<vspace blankLines="1"/>
+The number of output channels, C, is not constrained to match the number of
+ decoded channels (M+N).
+A single index value MAY appear multiple times, i.e., the same decoded channel
+ might be mapped to multiple output channels.
+Some decoded channels might not be assigned to any output channel, as well.
+<vspace blankLines="1"/>
+For channel mapping family&nbsp;0, the first index defaults to 0, and if C==2,
+ the second index defaults to 1.
+Neither index is coded.
+</t>
+</list>
+</t>
+
+<t>
+After producing the output channels, the channel mapping family determines the
+ semantic meaning of each one.
+Currently there are three defined mapping families, although more may be added.
+</t>
+
+<section anchor="channel_mapping_0" title="Channel Mapping Family 0">
+<t>
+Allowed numbers of channels: 1 or 2.
+RTP mapping.
+</t>
+<t>
+<list style="symbols">
+<t>1 channel: monophonic (mono).</t>
+<t>2 channels: stereo (left, right).</t>
+</list>
+<spanx style="strong">Special mapping</spanx>: This channel mapping value also
+ indicates that the contents consists of a single Opus stream that is stereo if
+ and only if C==2, with stream index 0 mapped to output channel 0 (mono, or
+ left channel) and stream index 1 mapped to output channel 1 (right channel)
+ if stereo.
+When the 'channel mapping family' octet has this value, the channel mapping
+ table MUST be omitted from the ID header packet.
+</t>
+</section>
+
+<section anchor="channel_mapping_1" title="Channel Mapping Family 1">
+<t>
+Allowed numbers of channels: 1...8.
+Vorbis channel order.
+</t>
+<t>
+Each channel is assigned to a speaker location in a conventional surround
+ configuration.
+Specific locations depend on the number of channels, and are given below
+ in order of the corresponding channel indicies.
+<list style="symbols">
+  <t>1 channel: monophonic (mono).</t>
+  <t>2 channels: stereo (left, right).</t>
+  <t>3 channels: linear surround (left, center, right)</t>
+  <t>4 channels: quadraphonic (front&nbsp;left, front&nbsp;right, rear&nbsp;left, rear&nbsp;right).</t>
+  <t>5 channels: 5.0 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, rear&nbsp;left, rear&nbsp;right).</t>
+  <t>6 channels: 5.1 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, rear&nbsp;left, rear&nbsp;right, LFE).</t>
+  <t>7 channels: 6.1 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, side&nbsp;left, side&nbsp;right, rear&nbsp;center, LFE).</t>
+  <t>8 channels: 7.1 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, side&nbsp;left, side&nbsp;right, rear&nbsp;left, rear&nbsp;right, LFE)</t>
+</list>
+This set of surround configurations and speaker location orderings is the same
+ as the one used by the Vorbis codec <xref target="vorbis-mapping"/>.
+The ordering is different from the one used by the
+ WAVE <xref target="wave-multichannel"/> and
+ FLAC <xref target="flac"/> formats,
+ so correct ordering requires permutation of the output channels when encoding
+ from or decoding to those formats.
+'LFE' here refers to a Low Frequency Effects, often mapped to a subwoofer
+ with no particular spacial position.
+Implementations SHOULD identify 'side' or 'rear' speaker locations with
+ 'surround' and 'back' as appropriate when interfacing with audio formats
+ or systems which prefer that terminology.
+Speaker configurations other than those described here are not supported.
+</t>
+</section>
+
+<section anchor="channel_mapping_255"
+ title="Channel Mapping Family 255">
+<t>
+Allowed numbers of channels: 1...255.
+No defined channel meaning.
+</t>
+<t>
+Channels are unidentified.
+General-purpose players SHOULD NOT attempt to play these streams, and offline
+ decoders MAY deinterleave the output into separate PCM files, one per channel.
+Decoders SHOULD NOT produce output for channels mapped to stream index 255
+ (pure silence) unless they have no other way to indicate the index of
+ non-silent channels.
+</t>
+</section>
+
+<section anchor="channel_mapping_undefined"
+ title="Undefined Channel Mappings">
+<t>
+The remaining channel mapping families (2...254) are reserved.
+A decoder encountering a reserved channel mapping family value SHOULD act as
+ though the value is 255.
+</t>
+</section>
+
+<section anchor="downmix" title="Downmixing">
+<t>
+An Ogg Opus player MUST play any Ogg Opus stream with a channel mapping family
+ of 0 or 1, even if the number of channels does not match the physically
+ connected audio hardware.
+Players SHOULD perform channel mixing to increase or reduce the number of
+ channels as needed.
+</t>
+
+<t>
+Implementations MAY use the following matricies to implement downmixing from
+ multichannel files using <xref target="channel_mapping_1">Channel Mapping
+ Family 1</xref>, which are known to give acceptable results for stereo.
+Matricies for 3 and 4 channels are normalized so each coefficent row sums
+ to 1 to avoid clipping.
+For 5 or more channels they are normalized to 2 as a compromize between
+ clipping and dynamic range reduction.
+</t>
+<t>
+In these matricies the front left and front right channels are generally
+passed through directly.
+When a surround channel is split between both the left and right stereo
+ channels, coefficients are chosen so their squares sum to 1, which
+ helps preserve the perceived intensity.
+Rear channels are mixed more diffusely or attenuated to maintain focus
+ on the front channels.
+</t>
+
+<figure anchor="downmix-matrix-3"
+ title="Stereo downmix matrix for the linear surround channel mapping"
+ align="center">
+<artwork align="center"><![CDATA[
+ Left output = ( 0.585786 * left + 0.414214 * center                    )
+Right output = (                   0.414214 * center + 0.585786 * right )
+]]></artwork>
+<postamble>
+Exact coefficient values are 1 and 1/sqrt(2), multiplied by
+ 1/(1 + 1/sqrt(2)) for normalization.
+</postamble>
+</figure>
+
+<figure anchor="downmix-matrix-4"
+ title="Stereo downmix matrix for the quadraphonic channel mapping"
+ align="center">
+<artwork align="center"><![CDATA[
+/          \   /                                     \ / FL \
+| L output |   | 0.422650 0.000000 0.366025 0.211325 | | FR |
+| R output | = | 0.000000 0.422650 0.211325 0.366025 | | RL |
+\          /   \                                     / \ RR /
+]]></artwork>
+<postamble>
+Exact coefficient values are 1, sqrt(3)/2 and 1/2, multiplied by
+ 1/(1&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2) for normalization.
+</postamble>
+</figure>
+
+<figure anchor="downmix-matrix-5"
+ title="Stereo downmix matrix for the 5.0 surround mapping"
+ align="center">
+<artwork align="center"><![CDATA[
+                                                         / FL \
+/   \   /                                              \ | FC |
+| L |   | 0.650802 0.460186 0.000000 0.563611 0.325401 | | FR |
+| R | = | 0.000000 0.460186 0.650802 0.325401 0.563611 | | RL |
+\   /   \                                              / | RR |
+                                                         \    /
+]]></artwork>
+<postamble>
+Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by
+ 2/(1&nbsp;+&nbsp;1/sqrt(2)&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2)
+ for normalization.
+</postamble>
+</figure>
+
+<figure anchor="downmix-matrix-6"
+ title="Stereo downmix matrix for the 5.1 surround mapping"
+ align="center">
+<artwork align="center"><![CDATA[
+                                                                /FL \
+/ \   /                                                       \ |FC |
+|L|   | 0.529067 0.374107 0.000000 0.458186 0.264534 0.374107 | |FR |
+|R| = | 0.000000 0.374107 0.529067 0.264534 0.458186 0.374107 | |RL |
+\ /   \                                                       / |RR |
+                                                                \LFE/
+]]></artwork>
+<postamble>
+Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by
+2/(1&nbsp;+&nbsp;1/sqrt(2)&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2 + 1/sqrt(2))
+ for normalization.
+</postamble>
+</figure>
+
+<figure anchor="downmix-matrix-7"
+ title="Stereo downmix matrix for the 6.1 surround mapping"
+ align="center">
+<artwork align="center"><![CDATA[
+ /                                                                \
+ | 0.455310 0.321953 0.000000 0.394310 0.227655 0.278819 0.321953 |
+ | 0.000000 0.321953 0.455310 0.227655 0.394310 0.278819 0.321953 |
+ \                                                                /
+]]></artwork>
+<postamble>
+Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2, 1/2 and
+ sqrt(3)/2/sqrt(2), multiplied by
+ 2/(1&nbsp;+&nbsp;1/sqrt(2)&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2 +
+ sqrt(3)/2/sqrt(2) + 1/sqrt(2)) for normalization.
+The coeffients are in the same order as in <xref target="channel_mapping_1" />,
+ and the matricies above.
+</postamble>
+</figure>
+
+<figure anchor="downmix-matrix-8"
+ title="Stereo downmix matrix for the 7.1 surround mapping"
+ align="center">
+<artwork align="center"><![CDATA[
+/                                                                 \
+| .388631 .274804 .000000 .336565 .194316 .336565 .194316 .274804 |
+| .000000 .274804 .388631 .194316 .336565 .194316 .336565 .274804 |
+\                                                                 /
+]]></artwork>
+<postamble>
+Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by
+ 2/(2&nbsp;+&nbsp;2/sqrt(2)&nbsp;+&nbsp;sqrt(3)) for normalization.
+The coeffients are in the same order as in <xref target="channel_mapping_1" />,
+ and the matricies above.
+</postamble>
+</figure>
+
+</section>
+
+</section> <!-- end channel_mapping_table -->
+
+</section> <!-- end id_header -->
+
+<section anchor="comment_header" title="Comment Header">
+
+<figure anchor="comment_header_packet" title="Comment Header Packet"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|      'O'      |      'p'      |      'u'      |      's'      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|      'T'      |      'a'      |      'g'      |      's'      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                     Vendor String Length                      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                        Vendor String...                       :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                   User Comment List Length                    |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                 User Comment #0 String Length                 |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                   User Comment #0 String...                   :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                 User Comment #1 String Length                 |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:                                                               :
+]]></artwork>
+</figure>
+
+<t>
+The comment header consists of a 64-bit magic signature, followed by data in
+ the same format as the <xref target="vorbis-comment"/> header used in Ogg
+ Vorbis (without the final "framing bit"), Ogg Theora, and Speex.
+<list style="numbers">
+<t><spanx style="strong">Magic Signature</spanx>:
+<vspace blankLines="1"/>
+This is an 8-octet (64-bit) field that allows codec identification and is
+ human-readable.
+It contains, in order, the magic numbers:
+<list style="empty">
+<t>0x4F 'O'</t>
+<t>0x70 'p'</t>
+<t>0x75 'u'</t>
+<t>0x73 's'</t>
+<t>0x54 'T'</t>
+<t>0x61 'a'</t>
+<t>0x67 'g'</t>
+<t>0x73 's'</t>
+</list>
+Starting with "Op" helps distinguish it from audio data packets, as this is an
+ invalid TOC sequence.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Vendor String Length</spanx> (32 bits, unsigned,
+ little endian):
+<vspace blankLines="1"/>
+This field gives the length of the following vendor string, in octets.
+It MUST NOT indicate that the vendor string is longer than the rest of the
+ packet.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">Vendor String</spanx> (variable length, UTF-8 vector):
+<vspace blankLines="1"/>
+This is a simple human-readable tag for vendor information, encoded as a UTF-8
+ string&nbsp;<xref target="RFC3629"/>.
+No terminating null octet is required.
+<vspace blankLines="1"/>
+This tag is intended to identify the codec encoder and encapsulation
+ implementations, for tracing differences in technical behavior.
+User-facing encoding applications can use the 'ENCODER' user comment tag
+ to identify themselves.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">User Comment List Length</spanx> (32 bits, unsigned,
+ little endian):
+<vspace blankLines="1"/>
+This field indicates the number of user-supplied comments.
+It MAY indicate there are zero user-supplied comments, in which case there are
+ no additional fields in the packet.
+It MUST NOT indicate that there are so many comments that the comment string
+ lengths would require more data than is available in the rest of the packet.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">User Comment #i String Length</spanx> (32 bits,
+ unsigned, little endian):
+<vspace blankLines="1"/>
+This field gives the length of the following user comment string, in octets.
+There is one for each user comment indicated by the 'user comment list length'
+ field.
+It MUST NOT indicate that the string is longer than the rest of the packet.
+<vspace blankLines="1"/>
+</t>
+<t><spanx style="strong">User Comment #i String</spanx> (variable length, UTF-8
+ vector):
+<vspace blankLines="1"/>
+This field contains a single user comment string.
+There is one for each user comment indicated by the 'user comment list length'
+ field.
+</t>
+</list>
+</t>
+
+<t>
+The vendor string length and user comment list length are REQUIRED, and
+ implementations SHOULD reject comment headers that do not contain enough data
+ for these fields, or that do not contain enough data for the corresponding
+ vendor string or user comments they describe.
+Making this check before allocating the associated memory to contain the data
+ may help prevent a possible Denial-of-Service (DoS) attack from small comment
+ headers that claim to contain strings longer than the entire packet or more
+ user comments than than could possibly fit in the packet.
+</t>
+
+<t>
+The user comment strings follow the NAME=value format described by
+ <xref target="vorbis-comment"/> with the same recommended tag names.
+One new comment tag is introduced for Ogg Opus:
+<figure align="center">
+<artwork align="left"><![CDATA[
+R128_TRACK_GAIN=-573
+]]></artwork>
+</figure>
+representing the volume shift needed to normalize the track's volume.
+The gain is a Q7.8 fixed point number in dB, as in the ID header's 'output
+ gain' field.
+This tag is similar to the REPLAYGAIN_TRACK_GAIN tag in
+ Vorbis&nbsp;<xref target="replay-gain"/>, except that the normal volume
+ reference is the <xref target="EBU-R128"/> standard.
+</t>
+<t>
+An Ogg Opus file MUST NOT have more than one such tag, and if present its
+ value MUST be an integer from -32768 to 32767, inclusive, represented in
+ ASCII with no whitespace.
+If present, it MUST correctly represent the R128 normalization gain relative
+ to the 'output gain' field specified in the ID header.
+If a player chooses to make use of the R128_TRACK_GAIN tag, it MUST be
+ applied <spanx style="emph">in addition</spanx> to the 'output gain' value.
+If an encoder wishes to use R128 normalization, and the output gain is not
+ otherwise constrained or specified, the encoder SHOULD write the R128 gain
+ into the 'output gain' field and store a tag containing "R128_TRACK_GAIN=0".
+That is, it should assume that by default tools will respect the 'output gain'
+ field, and not the comment tag.
+If a tool modifies the ID header's 'output gain' field, it MUST also update or
+ remove the R128_TRACK_GAIN comment tag.
+</t>
+<t>
+To avoid confusion with multiple normalization schemes, an Opus comment header
+ SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN, REPLAYGAIN_TRACK_PEAK,
+ REPLAYGAIN_ALBUM_GAIN, or REPLAYGAIN_ALBUM_PEAK tags.
+</t>
+<t>
+There is no Opus comment tag corresponding to REPLAYGAIN_ALBUM_GAIN.
+That information should instead be stored in the ID header's 'output gain'
+ field.
+</t>
+</section>
+
+</section>
+
+<section anchor="packet_size_limits" title="Packet Size Limits">
+<t>
+Technically valid Opus packets can be arbitrarily large due to the padding
+ format, although the amount of non-padding data they can contain is bounded.
+These packets might be spread over a similarly enormous number of Ogg pages.
+Encoders SHOULD use no more padding than required to make a variable bitrate
+ (VBR) stream constant bitrate (CBR).
+Decoders SHOULD avoid attempting to allocate excessive amounts of memory when
+ presented with a very large packet.
+The presence of an extremely large packet in the stream could indicate a
+ memory exhaustion attack or stream corruption.
+Decoders SHOULD reject a packet that is too large to process, and display a
+ warning message.
+</t>
+<t>
+In an Ogg Opus stream, the largest possible valid packet that does not use
+ padding has a size of (61,298*N&nbsp;-&nbsp;2) octets, or about 60&nbsp;kB per
+ Opus stream.
+With 255&nbsp;streams, this is 15,630,988&nbsp;octets (14.9&nbsp;MB) and can
+ span up to 61,298&nbsp;Ogg pages, all but one of which will have a granule
+ position of -1.
+This is of course a very extreme packet, consisting of 255&nbsp;streams, each
+ containing 120&nbsp;ms of audio encoded as 2.5&nbsp;ms frames, each frame
+ using the maximum possible number of octets (1275) and stored in the least
+ efficient manner allowed (a VBR code&nbsp;3 Opus packet).
+Even in such a packet, most of the data will be zeros as 2.5&nbsp;ms frames
+ cannot actually use all 1275&nbsp;octets.
+The largest packet consisting of entirely useful data is
+ (15,326*N&nbsp;-&nbsp;2) octets, or about 15&nbsp;kB per stream.
+This corresponds to 120&nbsp;ms of audio encoded as 10&nbsp;ms frames in either
+ LP or Hybrid mode, but at a data rate of over 1&nbsp;Mbps, which makes little
+ sense for the quality achieved.
+A more reasonable limit is (7,664*N&nbsp;-&nbsp;2) octets, or about 7.5&nbsp;kB
+ per stream.
+This corresponds to 120&nbsp;ms of audio encoded as 20&nbsp;ms stereo MDCT-mode
+ frames, with a total bitrate just under 511&nbsp;kbps (not counting the Ogg
+ encapsulation overhead).
+With N=8, the maximum number of channels currently defined by mapping
+ family&nbsp;1, this gives a maximum packet size of 61,310&nbsp;octets, or just
+ under 60&nbsp;kB.
+This is still quite conservative, as it assumes each output channel is taken
+ from one decoded channel of a stereo packet.
+An implementation could reasonably choose any of these numbers for its internal
+ limits.
+</t>
+</section>
+
+<section anchor="encoder" title="Encoder Guidelines">
+<t>
+When encoding Opus files, Ogg encoders should take into account the
+ algorithmic delay of the Opus encoder.
+</t>
+<figure align="center">
+<preamble>
+In encoders derived from the reference implementation, the number of
+ samples can be queried with:
+</preamble>
+<artwork align="center"><![CDATA[
+ opus_encoder_ctl(encoder_state, OPUS_GET_LOOKAHEAD, &samples_delay);
+]]></artwork>
+</figure>
+<t>
+To achieve good quality in the very first samples of a stream, the Ogg encoder
+ MAY use LPC extrapolation to generate at least 120 extra samples
+ (extra_samples) at the beginning to avoid the Opus encoder having to encode
+ a discontinuous signal.
+For an input file containing length samples, the Ogg encoder SHOULD set the
+ preskip header flag to samples_delay+extra_samples, encode at least
+ length+samples_delay+extra_samples samples, and set the granulepos of the last
+ page to length+samples_delay+extra_samples.
+This ensures that the encoded file has the same duration as the original, with
+ no time offset. The best way to pad the end of the stream is to also use LPC
+ extrapolation, but zero-padding is also acceptable.
+</t>
+
+<section anchor="lpc" title="LPC Extrapolation">
+<t>
+The first step in LPC extrapolation is to compute linear prediction
+ coefficients.
+When extending the end of the signal, order-N (typically with N ranging from 8
+ to 40) LPC analysis is performed on a window near the end of the signal.
+The last N samples are used as memory to an infinite impulse response (IIR)
+ filter.
+</t>
+<figure align="center">
+<preamble>
+The filter is then applied on a zero input to extrapolate the end of the signal.
+Let a(k) be the kth LPC coefficient and x(n) be the nth sample of the signal,
+ each new sample past the end of the signal is computed as:
+</preamble>
+<artwork align="center"><![CDATA[
+        N
+       ---
+x(n) = \   a(k)*x(n-k)
+       /
+       ---
+       k=1
+]]></artwork>
+</figure>
+<t>
+The process is repeated independently for each channel.
+It is possible to extend the beginning of the signal by applying the same
+ process backward in time.
+When extending the beginning of the signal, it is best to apply a "fade in" to
+ the extrapolated signal, e.g. by multiplying it by a half-Hanning window
+ <xref target="hanning"/>.
+</t>
+
+</section>
+
+<section anchor="continuous_chaining" title="Continuous Chaining">
+<t>
+In some applications, such as Internet radio, it is desirable to cut a long
+ streams into smaller chains, e.g. so the comment header can be updated.
+This can be done simply by separating the input streams into segments and
+ encoding each segment independently.
+The drawback of this approach is that it creates a small discontinuity
+ at the boundary due to the lossy nature of Opus.
+An encoder MAY avoid this discontinuity by using the following procedure:
+<list style="numbers">
+<t>Encode the last frame of the first segment as an independent frame by
+ turning off all forms of inter-frame prediction.
+De-emphasis is allowed.</t>
+<t>Set the granulepos of the last page to a point near the end of the last
+ frame.</t>
+<t>Begin the second segment with a copy of the last frame of the first
+ segment.</t>
+<t>Set the preskip flag of the second stream in such a way as to properly
+ join the two streams.</t>
+<t>Continue the encoding process normally from there, without any reset to
+ the encoder.</t>
+</list>
+</t>
+</section>
+
+</section>
+
+<section anchor="implementation" title="Implementation Status">
+<t>
+A brief summary of major implementations of this draft is available
+ at <eref target="https://wiki.xiph.org/OggOpusImplementation"/>,
+  along with their status.
+</t>
+<t>
+[Note to RFC Editor: please remove this entire section before
+ final publication per <xref target="draft-sheffer-running-code"/>.]
+</t>
+</section>
+
+<section anchor="security" title="Security Considerations">
+<t>
+Implementations of the Opus codec need to take appropriate security
+ considerations into account, as outlined in <xref target="RFC4732"/>.
+This is just as much a problem for the container as it is for the codec itself.
+It is extremely important for the decoder to be robust against malicious
+ payloads.
+Malicious payloads must not cause the decoder to overrun its allocated memory
+ or to take an excessive amount of resources to decode.
+Although problems in encoders are typically rarer, the same applies to the
+ encoder.
+Malicious audio streams must not cause the encoder to misbehave because this
+ would allow an attacker to attack transcoding gateways.
+</t>
+
+<t>
+Like most other container formats, Ogg Opus files should not be used with
+ insecure ciphers or cipher modes that are vulnerable to known-plaintext
+ attacks.
+Elements such as the Ogg page capture pattern and the magic signatures in the
+ ID header and the comment header all have easily predictable values, in
+ addition to various elements of the codec data itself.
+</t>
+</section>
+
+<section anchor="content_type" title="Content Type">
+<t>
+An "Ogg Opus file" consists of one or more sequentially multiplexed segments,
+ each containing exactly one Ogg Opus stream.
+The RECOMMENDED mime-type for Ogg Opus files is "audio/ogg".
+</t>
+
+<figure>
+<preamble>
+If more specificity is desired, one MAY indicate the presence of Opus streams
+ using the codecs parameter defined in <xref target="RFC6381"/>, e.g.,
+</preamble>
+<artwork align="center"><![CDATA[
+    audio/ogg; codecs=opus
+]]></artwork>
+<postamble>
+ for an Ogg Opus file.
+</postamble>
+</figure>
+
+<t>
+The RECOMMENDED filename extension for Ogg Opus files is '.opus'.
+</t>
+
+<t>
+When Opus is concurrently multiplexed with other streams in an Ogg container,
+ one SHOULD use one of the "audio/ogg", "video/ogg", or "application/ogg"
+ mime-types, as defined in <xref target="RFC5334"/>.
+Such streams are not strictly "Ogg Opus files" as described above,
+ since they contain more than a single Opus stream per sequentially
+ multiplexed segment, e.g. video or multiple audio tracks.
+In such cases the the '.opus' filename extension is NOT RECOMMENDED.
+</t>
+</section>
+
+<section title="IANA Considerations">
+<t>
+This document has no actions for IANA.
+</t>
+</section>
+
+<section anchor="Acknowledgments" title="Acknowledgments">
+<t>
+Thanks to Greg Maxwell, Christopher "Monty" Montgomery, and Jean-Marc Valin for
+ their valuable contributions to this document.
+Additional thanks to Andrew D'Addesio, Greg Maxwell, and Vincent Penqeurc'h for
+ their feedback based on early implementations.
+</t>
+</section>
+
+<section title="Copying Conditions">
+<t>
+The authors agree to grant third parties the irrevocable right to copy, use,
+ and distribute the work, with or without modification, in any medium, without
+ royalty, provided that, unless separate permission is granted, redistributed
+ modified works do not contain misleading author, version, name of work, or
+ endorsement information.
+</t>
+</section>
+
+</middle>
+<back>
+<references title="Normative References">
+ &rfc2119;
+ &rfc3533;
+ &rfc3629;
+ &rfc5334;
+ &rfc6381;
+ &rfc6716;
+
+<reference anchor="EBU-R128" target="http://tech.ebu.ch/loudness">
+<front>
+<title>"Loudness Recommendation EBU R128</title>
+<author fullname="EBU Technical Committee"/>
+<date month="August" year="2011"/>
+</front>
+</reference>
+
+<reference anchor="vorbis-comment"
+ target="http://www.xiph.org/vorbis/doc/v-comment.html">
+<front>
+<title>Ogg Vorbis I Format Specification: Comment Field and Header
+ Specification</title>
+<author initials="C." surname="Montgomery"
+ fullname="Christopher &quot;Monty&quot; Montgomery"/>
+<date month="July" year="2002"/>
+</front>
+</reference>
+
+</references>
+
+<references title="Informative References">
+
+<!--?rfc include="http://xml.resource.org/public/rfc/bibxml/reference.RFC.3550.xml"?-->
+ &rfc4732;
+
+<reference anchor="draft-sheffer-running-code"
+  target="https://tools.ietf.org/html/draft-sheffer-running-code-05#section-2">
+ <front>
+   <title>Improving "Rough Consensus" with Running Code</title>
+   <author initials="Y." surname="Sheffer" fullname="Yaron Sheffer"/>
+   <author initials="A." surname="Farrel" fullname="Adrian Farrel"/>
+   <date month="May" year="2013"/>
+ </front>
+</reference>
+
+<reference anchor="flac"
+ target="https://xiph.org/flac/format.html">
+  <front>
+    <title>FLAC - Free Lossless Audio Codec Format Description</title>
+    <author initials="J." surname="Coalson" fullname="Josh Coalson"/>
+    <date month="January" year="2008"/>
+  </front>
+</reference>
+
+<reference anchor="hanning"
+ target="http://en.wikipedia.org/wiki/Hamming_function#Hann_.28Hanning.29_window">
+  <front>
+    <title>"Hann window</title>
+    <author fullname="Wikipedia"/>
+    <date month="May" year="2013"/>
+  </front>
+</reference>
+
+<reference anchor="replay-gain"
+ target="http://wiki.xiph.org/VorbisComment#Replay_Gain">
+<front>
+<title>VorbisComment: Replay Gain</title>
+<author initials="C." surname="Parker" fullname="Conrad Parker"/>
+<author initials="M." surname="Leese" fullname="Martin Leese"/>
+<date month="June" year="2009"/>
+</front>
+</reference>
+
+<reference anchor="seeking"
+ target="http://wiki.xiph.org/Seeking">
+<front>
+<title>Granulepos Encoding and How Seeking Really Works</title>
+<author initials="S." surname="Pfeiffer" fullname="Silvia Pfeiffer"/>
+<author initials="C." surname="Parker" fullname="Conrad Parker"/>
+<author initials="G." surname="Maxwell" fullname="Greg Maxwell"/>
+<date month="May" year="2012"/>
+</front>
+</reference>
+
+<reference anchor="vorbis-mapping"
+ target="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">
+<front>
+<title>The Vorbis I Specification, Section 4.3.9 Output Channel Order</title>
+<author initials="C." surname="Montgomery"
+ fullname="Christopher &quot;Monty&quot; Montgomery"/>
+<date month="January" year="2010"/>
+</front>
+</reference>
+
+<reference anchor="vorbis-trim"
+ target="http://xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-130000A.2">
+  <front>
+    <title>The Vorbis I Specification, Appendix&nbsp;A: Embedding Vorbis
+      into an Ogg stream</title>
+    <author initials="C." surname="Montgomery"
+     fullname="Christopher &quot;Monty&quot; Montgomery"/>
+    <date month="November" year="2008"/>
+  </front>
+</reference>
+
+<reference anchor="wave-multichannel"
+ target="http://msdn.microsoft.com/en-us/windows/hardware/gg463006.aspx">
+  <front>
+    <title>Multiple Channel Audio Data and WAVE Files</title>
+    <author fullname="Microsoft Corporation"/>
+    <date month="March" year="2007"/>
+  </front>
+</reference>
+
+</references>
+
+</back>
+</rfc>
diff --git a/doc/draft-ietf-codec-opus.xml b/doc/draft-ietf-codec-opus.xml
new file mode 100644
index 0000000..334cad9
--- /dev/null
+++ b/doc/draft-ietf-codec-opus.xml
@@ -0,0 +1,8276 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE rfc SYSTEM 'rfc2629.dtd'>
+<?rfc toc="yes" symrefs="yes" ?>
+
+<rfc ipr="trust200902" category="std" docName="draft-ietf-codec-opus-14">
+
+<front>
+<title abbrev="Interactive Audio Codec">Definition of the Opus Audio Codec</title>
+
+
+<author initials="JM" surname="Valin" fullname="Jean-Marc Valin">
+<organization>Mozilla Corporation</organization>
+<address>
+<postal>
+<street>650 Castro Street</street>
+<city>Mountain View</city>
+<region>CA</region>
+<code>94041</code>
+<country>USA</country>
+</postal>
+<phone>+1 650 903-0800</phone>
+<email>jmvalin@jmvalin.ca</email>
+</address>
+</author>
+
+<author initials="K." surname="Vos" fullname="Koen Vos">
+<organization>Skype Technologies S.A.</organization>
+<address>
+<postal>
+<street>Soder Malarstrand 43</street>
+<city>Stockholm</city>
+<region></region>
+<code>11825</code>
+<country>SE</country>
+</postal>
+<phone>+46 73 085 7619</phone>
+<email>koen.vos@skype.net</email>
+</address>
+</author>
+
+<author initials="T." surname="Terriberry" fullname="Timothy B. Terriberry">
+<organization>Mozilla Corporation</organization>
+<address>
+<postal>
+<street>650 Castro Street</street>
+<city>Mountain View</city>
+<region>CA</region>
+<code>94041</code>
+<country>USA</country>
+</postal>
+<phone>+1 650 903-0800</phone>
+<email>tterriberry@mozilla.com</email>
+</address>
+</author>
+
+<date day="17" month="May" year="2012" />
+
+<area>General</area>
+
+<workgroup></workgroup>
+
+<abstract>
+<t>
+This document defines the Opus interactive speech and audio codec.
+Opus is designed to handle a wide range of interactive audio applications,
+ including Voice over IP, videoconferencing, in-game chat, and even live,
+ distributed music performances.
+It scales from low bitrate narrowband speech at 6 kb/s to very high quality
+ stereo music at 510 kb/s.
+Opus uses both linear prediction (LP) and the Modified Discrete Cosine
+ Transform (MDCT) to achieve good compression of both speech and music.
+</t>
+</abstract>
+</front>
+
+<middle>
+
+<section anchor="introduction" title="Introduction">
+<t>
+The Opus codec is a real-time interactive audio codec designed to meet the requirements
+described in <xref target="requirements"></xref>.
+It is composed of a linear
+ prediction (LP)-based <xref target="LPC"/> layer and a Modified Discrete Cosine Transform
+ (MDCT)-based <xref target="MDCT"/> layer.
+The main idea behind using two layers is that in speech, linear prediction
+ techniques (such as Code-Excited Linear Prediction, or CELP) code low frequencies more efficiently than transform
+ (e.g., MDCT) domain techniques, while the situation is reversed for music and
+ higher speech frequencies.
+Thus a codec with both layers available can operate over a wider range than
+ either one alone and, by combining them, achieve better quality than either
+ one individually.
+</t>
+
+<t>
+The primary normative part of this specification is provided by the source code
+ in <xref target="ref-implementation"></xref>.
+Only the decoder portion of this software is normative, though a
+ significant amount of code is shared by both the encoder and decoder.
+<xref target="conformance"/> provides a decoder conformance test.
+The decoder contains a great deal of integer and fixed-point arithmetic which
+ needs to be performed exactly, including all rounding considerations, so any
+ useful specification requires domain-specific symbolic language to adequately
+ define these operations.
+Additionally, any
+conflict between the symbolic representation and the included reference
+implementation must be resolved. For the practical reasons of compatibility and
+testability it would be advantageous to give the reference implementation
+priority in any disagreement. The C language is also one of the most
+widely understood human-readable symbolic representations for machine
+behavior.
+For these reasons this RFC uses the reference implementation as the sole
+ symbolic representation of the codec.
+</t>
+
+<t>While the symbolic representation is unambiguous and complete it is not
+always the easiest way to understand the codec's operation. For this reason
+this document also describes significant parts of the codec in English and
+takes the opportunity to explain the rationale behind many of the more
+surprising elements of the design. These descriptions are intended to be
+accurate and informative, but the limitations of common English sometimes
+result in ambiguity, so it is expected that the reader will always read
+them alongside the symbolic representation. Numerous references to the
+implementation are provided for this purpose. The descriptions sometimes
+differ from the reference in ordering or through mathematical simplification
+wherever such deviation makes an explanation easier to understand.
+For example, the right shift and left shift operations in the reference
+implementation are often described using division and multiplication in the text.
+In general, the text is focused on the "what" and "why" while the symbolic
+representation most clearly provides the "how".
+</t>
+
+<section anchor="notation" title="Notation and Conventions">
+<t>
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
+ "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
+ interpreted as described in RFC 2119 <xref target="rfc2119"></xref>.
+</t>
+<t>
+Various operations in the codec require bit-exact fixed-point behavior, even
+ when writing a floating point implementation.
+The notation "Q&lt;n&gt;", where n is an integer, denotes the number of binary
+ digits to the right of the decimal point in a fixed-point number.
+For example, a signed Q14 value in a 16-bit word can represent values from
+ -2.0 to 1.99993896484375, inclusive.
+This notation is for informational purposes only.
+Arithmetic, when described, always operates on the underlying integer.
+E.g., the text will explicitly indicate any shifts required after a
+ multiplication.
+</t>
+<t>
+Expressions, where included in the text, follow C operator rules and
+ precedence, with the exception that the syntax "x**y" indicates x raised to
+ the power y.
+The text also makes use of the following functions:
+</t>
+
+<section anchor="min" toc="exclude" title="min(x,y)">
+<t>
+The smallest of two values x and y.
+</t>
+</section>
+
+<section anchor="max" toc="exclude" title="max(x,y)">
+<t>
+The largest of two values x and y.
+</t>
+</section>
+
+<section anchor="clamp" toc="exclude" title="clamp(lo,x,hi)">
+<figure align="center">
+<artwork align="center"><![CDATA[
+clamp(lo,x,hi) = max(lo,min(x,hi))
+]]></artwork>
+</figure>
+<t>
+With this definition, if lo&nbsp;&gt;&nbsp;hi, the lower bound is the one that
+ is enforced.
+</t>
+</section>
+
+<section anchor="sign" toc="exclude" title="sign(x)">
+<t>
+The sign of x, i.e.,
+<figure align="center">
+<artwork align="center"><![CDATA[
+          ( -1,  x < 0 ,
+sign(x) = <  0,  x == 0 ,
+          (  1,  x > 0 .
+]]></artwork>
+</figure>
+</t>
+</section>
+
+<section anchor="abs" toc="exclude" title="abs(x)">
+<t>
+The absolute value of x, i.e.,
+<figure align="center">
+<artwork align="center"><![CDATA[
+abs(x) = sign(x)*x .
+]]></artwork>
+</figure>
+</t>
+</section>
+
+<section anchor="floor" toc="exclude" title="floor(f)">
+<t>
+The largest integer z such that z &lt;= f.
+</t>
+</section>
+
+<section anchor="ceil" toc="exclude" title="ceil(f)">
+<t>
+The smallest integer z such that z &gt;= f.
+</t>
+</section>
+
+<section anchor="round" toc="exclude" title="round(f)">
+<t>
+The integer z nearest to f, with ties rounded towards negative infinity,
+ i.e.,
+<figure align="center">
+<artwork align="center"><![CDATA[
+ round(f) = ceil(f - 0.5) .
+]]></artwork>
+</figure>
+</t>
+</section>
+
+<section anchor="log2" toc="exclude" title="log2(f)">
+<t>
+The base-two logarithm of f.
+</t>
+</section>
+
+<section anchor="ilog" toc="exclude" title="ilog(n)">
+<t>
+The minimum number of bits required to store a positive integer n in two's
+ complement notation, or 0 for a non-positive integer n.
+<figure align="center">
+<artwork align="center"><![CDATA[
+          ( 0,                 n <= 0,
+ilog(n) = <
+          ( floor(log2(n))+1,  n > 0
+]]></artwork>
+</figure>
+Examples:
+<list style="symbols">
+<t>ilog(-1) = 0</t>
+<t>ilog(0) = 0</t>
+<t>ilog(1) = 1</t>
+<t>ilog(2) = 2</t>
+<t>ilog(3) = 2</t>
+<t>ilog(4) = 3</t>
+<t>ilog(7) = 3</t>
+</list>
+</t>
+</section>
+
+</section>
+
+</section>
+
+<section anchor="overview" title="Opus Codec Overview">
+
+<t>
+The Opus codec scales from 6&nbsp;kb/s narrowband mono speech to 510&nbsp;kb/s
+ fullband stereo music, with algorithmic delays ranging from 5&nbsp;ms to
+ 65.2&nbsp;ms.
+At any given time, either the LP layer, the MDCT layer, or both, may be active.
+It can seamlessly switch between all of its various operating modes, giving it
+ a great deal of flexibility to adapt to varying content and network
+ conditions without renegotiating the current session.
+The codec allows input and output of various audio bandwidths, defined as
+ follows:
+</t>
+<texttable anchor="audio-bandwidth">
+<ttcol>Abbreviation</ttcol>
+<ttcol align="right">Audio Bandwidth</ttcol>
+<ttcol align="right">Sample Rate (Effective)</ttcol>
+<c>NB (narrowband)</c>       <c>4&nbsp;kHz</c>  <c>8&nbsp;kHz</c>
+<c>MB (medium-band)</c>      <c>6&nbsp;kHz</c> <c>12&nbsp;kHz</c>
+<c>WB (wideband)</c>         <c>8&nbsp;kHz</c> <c>16&nbsp;kHz</c>
+<c>SWB (super-wideband)</c> <c>12&nbsp;kHz</c> <c>24&nbsp;kHz</c>
+<c>FB (fullband)</c>        <c>20&nbsp;kHz (*)</c> <c>48&nbsp;kHz</c>
+</texttable>
+<t>
+(*) Although the sampling theorem allows a bandwidth as large as half the
+ sampling rate, Opus never codes audio above 20&nbsp;kHz, as that is the
+ generally accepted upper limit of human hearing.
+</t>
+
+<t>
+Opus defines super-wideband (SWB) with an effective sample rate of 24&nbsp;kHz,
+ unlike some other audio coding standards that use 32&nbsp;kHz.
+This was chosen for a number of reasons.
+The band layout in the MDCT layer naturally allows skipping coefficients for
+ frequencies over 12&nbsp;kHz, but does not allow cleanly dropping just those
+ frequencies over 16&nbsp;kHz.
+A sample rate of 24&nbsp;kHz also makes resampling in the MDCT layer easier,
+ as 24 evenly divides 48, and when 24&nbsp;kHz is sufficient, it can save
+ computation in other processing, such as Acoustic Echo Cancellation (AEC).
+Experimental changes to the band layout to allow a 16&nbsp;kHz cutoff
+ (32&nbsp;kHz effective sample rate) showed potential quality degradations at
+ other sample rates, and at typical bitrates the number of bits saved by using
+ such a cutoff instead of coding in fullband (FB) mode is very small.
+Therefore, if an application wishes to process a signal sampled at 32&nbsp;kHz,
+ it should just use FB.
+</t>
+
+<t>
+The LP layer is based on the SILK codec
+ <xref target="SILK"></xref>.
+It supports NB, MB, or WB audio and frame sizes from 10&nbsp;ms to 60&nbsp;ms,
+ and requires an additional 5&nbsp;ms look-ahead for noise shaping estimation.
+A small additional delay (up to 1.5 ms) may be required for sampling rate
+ conversion.
+Like Vorbis <xref target='Vorbis-website'/> and many other modern codecs, SILK is inherently designed for
+ variable-bitrate (VBR) coding, though the encoder can also produce
+ constant-bitrate (CBR) streams.
+The version of SILK used in Opus is substantially modified from, and not
+ compatible with, the stand-alone SILK codec previously deployed by Skype.
+This document does not serve to define that format, but those interested in the
+ original SILK codec should see <xref target="SILK"/> instead.
+</t>
+
+<t>
+The MDCT layer is based on the CELT  codec <xref target="CELT"></xref>.
+It supports NB, WB, SWB, or FB audio and frame sizes from 2.5&nbsp;ms to
+ 20&nbsp;ms, and requires an additional 2.5&nbsp;ms look-ahead due to the
+ overlapping MDCT windows.
+The CELT codec is inherently designed for CBR coding, but unlike many CBR
+ codecs it is not limited to a set of predetermined rates.
+It internally allocates bits to exactly fill any given target budget, and an
+ encoder can produce a VBR stream by varying the target on a per-frame basis.
+The MDCT layer is not used for speech when the audio bandwidth is WB or less,
+ as it is not useful there.
+On the other hand, non-speech signals are not always adequately coded using
+ linear prediction, so for music only the MDCT layer should be used.
+</t>
+
+<t>
+A "Hybrid" mode allows the use of both layers simultaneously with a frame size
+ of 10&nbsp;or 20&nbsp;ms and a SWB or FB audio bandwidth.
+The LP layer codes the low frequencies by resampling the signal down to WB.
+The MDCT layer follows, coding the high frequency portion of the signal.
+The cutoff between the two lies at 8&nbsp;kHz, the maximum WB audio bandwidth.
+In the MDCT layer, all bands below 8&nbsp;kHz are discarded, so there is no
+ coding redundancy between the two layers.
+</t>
+
+<t>
+The sample rate (in contrast to the actual audio bandwidth) can be chosen
+ independently on the encoder and decoder side, e.g., a fullband signal can be
+ decoded as wideband, or vice versa.
+This approach ensures a sender and receiver can always interoperate, regardless
+ of the capabilities of their actual audio hardware.
+Internally, the LP layer always operates at a sample rate of twice the audio
+ bandwidth, up to a maximum of 16&nbsp;kHz, which it continues to use for SWB
+ and FB.
+The decoder simply resamples its output to support different sample rates.
+The MDCT layer always operates internally at a sample rate of 48&nbsp;kHz.
+Since all the supported sample rates evenly divide this rate, and since the
+ the decoder may easily zero out the high frequency portion of the spectrum in
+ the frequency domain, it can simply decimate the MDCT layer output to achieve
+ the other supported sample rates very cheaply.
+</t>
+
+<t>
+After conversion to the common, desired output sample rate, the decoder simply
+ adds the output from the two layers together.
+To compensate for the different look-ahead required by each layer, the CELT
+ encoder input is delayed by an additional 2.7&nbsp;ms.
+This ensures that low frequencies and high frequencies arrive at the same time.
+This extra delay may be reduced by an encoder by using less look-ahead for noise
+ shaping or using a simpler resampler in the LP layer, but this will reduce
+ quality.
+However, the base 2.5&nbsp;ms look-ahead in the CELT layer cannot be reduced in
+ the encoder because it is needed for the MDCT overlap, whose size is fixed by
+ the decoder.
+</t>
+
+<t>
+Both layers use the same entropy coder, avoiding any waste from "padding bits"
+ between them.
+The hybrid approach makes it easy to support both CBR and VBR coding.
+Although the LP layer is VBR, the bit allocation of the MDCT layer can produce
+ a final stream that is CBR by using all the bits left unused by the LP layer.
+</t>
+
+<section title="Control Parameters">
+<t>
+The Opus codec includes a number of control parameters which can be changed dynamically during
+regular operation of the codec, without interrupting the audio stream from the encoder to the decoder.
+These parameters only affect the encoder since any impact they have on the bit-stream is signaled
+in-band such that a decoder can decode any Opus stream without any out-of-band signaling. Any Opus
+implementation can add or modify these control parameters without affecting interoperability. The most
+important encoder control parameters in the reference encoder are listed below.
+</t>
+
+<section title="Bitrate" toc="exlcude">
+<t>
+Opus supports all bitrates from 6&nbsp;kb/s to 510&nbsp;kb/s. All other parameters being
+equal, higher bitrate results in higher quality. For a frame size of 20&nbsp;ms, these
+are the bitrate "sweet spots" for Opus in various configurations:
+<list style="symbols">
+<t>8-12 kb/s for NB speech,</t>
+<t>16-20 kb/s for WB speech,</t>
+<t>28-40 kb/s for FB speech,</t>
+<t>48-64 kb/s for FB mono music, and</t>
+<t>64-128 kb/s for FB stereo music.</t>
+</list>
+</t>
+</section>
+
+<section title="Number of Channels (Mono/Stereo)" toc="exlcude">
+<t>
+Opus can transmit either mono or stereo frames within a single stream.
+When decoding a mono frame in a stereo decoder, the left and right channels are
+ identical, and when decoding a stereo frame in a mono decoder, the mono output
+ is the average of the left and right channels.
+In some cases, it is desirable to encode a stereo input stream in mono (e.g.,
+ because the bitrate is too low to encode stereo with sufficient quality).
+The number of channels encoded can be selected in real-time, but by default the
+ reference encoder attempts to make the best decision possible given the
+ current bitrate.
+</t>
+</section>
+
+<section title="Audio Bandwidth" toc="exlcude">
+<t>
+The audio bandwidths supported by Opus are listed in
+ <xref target="audio-bandwidth"/>.
+Just like for the number of channels, any decoder can decode audio encoded at
+ any bandwidth.
+For example, any Opus decoder operating at 8&nbsp;kHz can decode a FB Opus
+ frame, and any Opus decoder operating at 48&nbsp;kHz can decode a NB frame.
+Similarly, the reference encoder can take a 48&nbsp;kHz input signal and
+ encode it as NB.
+The higher the audio bandwidth, the higher the required bitrate to achieve
+ acceptable quality.
+The audio bandwidth can be explicitly specified in real-time, but by default
+ the reference encoder attempts to make the best bandwidth decision possible
+ given the current bitrate.
+</t>
+</section>
+
+
+<section title="Frame Duration" toc="exlcude">
+<t>
+Opus can encode frames of 2.5, 5, 10, 20, 40 or 60&nbsp;ms.
+It can also combine multiple frames into packets of up to 120&nbsp;ms.
+For real-time applications, sending fewer packets per second reduces the
+ bitrate, since it reduces the overhead from IP, UDP, and RTP headers.
+However, it increases latency and sensitivity to packet losses, as losing one
+ packet constitutes a loss of a bigger chunk of audio.
+Increasing the frame duration also slightly improves coding efficiency, but the
+ gain becomes small for frame sizes above 20&nbsp;ms.
+For this reason, 20&nbsp;ms frames are a good choice for most applications.
+</t>
+</section>
+
+<section title="Complexity" toc="exlcude">
+<t>
+There are various aspects of the Opus encoding process where trade-offs
+can be made between CPU complexity and quality/bitrate. In the reference
+encoder, the complexity is selected using an integer from 0 to 10, where
+0 is the lowest complexity and 10 is the highest. Examples of
+computations for which such trade-offs may occur are:
+<list style="symbols">
+<t>The order of the pitch analysis whitening filter <xref target="Whitening"/>,</t>
+<t>The order of the short-term noise shaping filter,</t>
+<t>The number of states in delayed decision quantization of the
+residual signal, and</t>
+<t>The use of certain bit-stream features such as variable time-frequency
+resolution and the pitch post-filter.</t>
+</list>
+</t>
+</section>
+
+<section title="Packet Loss Resilience" toc="exlcude">
+<t>
+Audio codecs often exploit inter-frame correlations to reduce the
+bitrate at a cost in error propagation: after losing one packet
+several packets need to be received before the decoder is able to
+accurately reconstruct the speech signal.  The extent to which Opus
+exploits inter-frame dependencies can be adjusted on the fly to
+choose a trade-off between bitrate and amount of error propagation.
+</t>
+</section>
+
+<section title="Forward Error Correction (FEC)" toc="exlcude">
+<t>
+   Another mechanism providing robustness against packet loss is the in-band
+   Forward Error Correction (FEC).  Packets that are determined to
+   contain perceptually important speech information, such as onsets or
+   transients, are encoded again at a lower bitrate and this re-encoded
+   information is added to a subsequent packet.
+</t>
+</section>
+
+<section title="Constant/Variable Bitrate" toc="exlcude">
+<t>
+Opus is more efficient when operating with variable bitrate (VBR), which is
+the default. However, in some (rare) applications, constant bitrate (CBR)
+is required. There are two main reasons to operate in CBR mode:
+<list style="symbols">
+<t>When the transport only supports a fixed size for each compressed frame</t>
+<t>When encryption is used for an audio stream that is either highly constrained
+   (e.g. yes/no, recorded prompts) or highly sensitive <xref target="SRTP-VBR"></xref> </t>
+</list>
+
+When low-latency transmission is required over a relatively slow connection, then
+constrained VBR can also be used. This uses VBR in a way that simulates a
+"bit reservoir" and is equivalent to what MP3 (MPEG 1, Layer 3) and
+AAC (Advanced Audio Coding) call CBR (i.e., not true
+CBR due to the bit reservoir).
+</t>
+</section>
+
+<section title="Discontinuous Transmission (DTX)" toc="exlcude">
+<t>
+   Discontinuous Transmission (DTX) reduces the bitrate during silence
+   or background noise.  When DTX is enabled, only one frame is encoded
+   every 400 milliseconds.
+</t>
+</section>
+
+</section>
+
+</section>
+
+<section anchor="modes" title="Internal Framing">
+
+<t>
+The Opus encoder produces "packets", which are each a contiguous set of bytes
+ meant to be transmitted as a single unit.
+The packets described here do not include such things as IP, UDP, or RTP
+ headers which are normally found in a transport-layer packet.
+A single packet may contain multiple audio frames, so long as they share a
+ common set of parameters, including the operating mode, audio bandwidth, frame
+ size, and channel count (mono vs. stereo).
+This section describes the possible combinations of these parameters and the
+ internal framing used to pack multiple frames into a single packet.
+This framing is not self-delimiting.
+Instead, it assumes that a higher layer (such as UDP or RTP <xref target='RFC3550'/>
+or Ogg <xref target='RFC3533'/> or Matroska <xref target='Matroska-website'/>)
+ will communicate the length, in bytes, of the packet, and it uses this
+ information to reduce the framing overhead in the packet itself.
+A decoder implementation MUST support the framing described in this section.
+An alternative, self-delimiting variant of the framing is described in
+ <xref target="self-delimiting-framing"/>.
+Support for that variant is OPTIONAL.
+</t>
+
+<t>
+All bit diagrams in this document number the bits so that bit 0 is the most
+ significant bit of the first byte, and bit 7 is the least significant.
+Bit 8 is thus the most significant bit of the second byte, etc.
+Well-formed Opus packets obey certain requirements, marked [R1] through [R7]
+ below.
+These are summarized in <xref target="malformed-packets"/> along with
+ appropriate means of handling malformed packets.
+</t>
+
+<section anchor="toc_byte" title="The TOC Byte">
+<t anchor="R1">
+A well-formed Opus packet MUST contain at least one byte&nbsp;[R1].
+This byte forms a table-of-contents (TOC) header that signals which of the
+ various modes and configurations a given packet uses.
+It is composed of a configuration number, "config", a stereo flag, "s", and a
+ frame count code, "c", arranged as illustrated in
+ <xref target="toc_byte_fig"/>.
+A description of each of these fields follows.
+</t>
+
+<figure anchor="toc_byte_fig" title="The TOC Byte">
+<artwork align="center"><![CDATA[
+ 0
+ 0 1 2 3 4 5 6 7
++-+-+-+-+-+-+-+-+
+| config  |s| c |
++-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+The top five bits of the TOC byte, labeled "config", encode one of 32 possible
+ configurations of operating mode, audio bandwidth, and frame size.
+As described, the LP (SILK) layer and MDCT (CELT) layer can be combined in three possible
+ operating modes:
+<list style="numbers">
+<t>A SILK-only mode for use in low bitrate connections with an audio bandwidth
+ of WB or less,</t>
+<t>A Hybrid (SILK+CELT) mode for SWB or FB speech at medium bitrates, and</t>
+<t>A CELT-only mode for very low delay speech transmission as well as music
+ transmission (NB to FB).</t>
+</list>
+The 32 possible configurations each identify which one of these operating modes
+ the packet uses, as well as the audio bandwidth and the frame size.
+<xref target="config_bits"/> lists the parameters for each configuration.
+</t>
+<texttable anchor="config_bits" title="TOC Byte Configuration Parameters">
+<ttcol>Configuration Number(s)</ttcol>
+<ttcol>Mode</ttcol>
+<ttcol>Bandwidth</ttcol>
+<ttcol>Frame Sizes</ttcol>
+<c>0...3</c>   <c>SILK-only</c> <c>NB</c>  <c>10, 20, 40, 60&nbsp;ms</c>
+<c>4...7</c>   <c>SILK-only</c> <c>MB</c>  <c>10, 20, 40, 60&nbsp;ms</c>
+<c>8...11</c>  <c>SILK-only</c> <c>WB</c>  <c>10, 20, 40, 60&nbsp;ms</c>
+<c>12...13</c> <c>Hybrid</c>    <c>SWB</c> <c>10, 20&nbsp;ms</c>
+<c>14...15</c> <c>Hybrid</c>    <c>FB</c>  <c>10, 20&nbsp;ms</c>
+<c>16...19</c> <c>CELT-only</c> <c>NB</c>  <c>2.5, 5, 10, 20&nbsp;ms</c>
+<c>20...23</c> <c>CELT-only</c> <c>WB</c>  <c>2.5, 5, 10, 20&nbsp;ms</c>
+<c>24...27</c> <c>CELT-only</c> <c>SWB</c> <c>2.5, 5, 10, 20&nbsp;ms</c>
+<c>28...31</c> <c>CELT-only</c> <c>FB</c>  <c>2.5, 5, 10, 20&nbsp;ms</c>
+</texttable>
+<t>
+The configuration numbers in each range (e.g., 0...3 for NB SILK-only)
+ correspond to the various choices of frame size, in the same order.
+For example, configuration 0 has a 10&nbsp;ms frame size and configuration 3
+ has a 60&nbsp;ms frame size.
+</t>
+
+<t>
+One additional bit, labeled "s", signals mono vs. stereo, with 0 indicating
+ mono and 1 indicating stereo.
+</t>
+
+<t>
+The remaining two bits of the TOC byte, labeled "c", code the number of frames
+ per packet (codes 0 to 3) as follows:
+<list style="symbols">
+<t>0:    1 frame in the packet</t>
+<t>1:    2 frames in the packet, each with equal compressed size</t>
+<t>2:    2 frames in the packet, with different compressed sizes</t>
+<t>3:    an arbitrary number of frames in the packet</t>
+</list>
+This draft refers to a packet as a code 0 packet, code 1 packet, etc., based on
+ the value of "c".
+</t>
+
+</section>
+
+<section title="Frame Packing">
+
+<t>
+This section describes how frames are packed according to each possible value
+ of "c" in the TOC byte.
+</t>
+
+<section anchor="frame-length-coding" title="Frame Length Coding">
+<t>
+When a packet contains multiple VBR frames (i.e., code 2 or 3), the compressed
+ length of one or more of these frames is indicated with a one- or two-byte
+ sequence, with the meaning of the first byte as follows:
+<list style="symbols">
+<t>0:          No frame (discontinuous transmission (DTX) or lost packet)</t>
+<t>1...251:    Length of the frame in bytes</t>
+<t>252...255:  A second byte is needed. The total length is (second_byte*4)+first_byte</t>
+</list>
+</t>
+
+<t>
+The special length 0 indicates that no frame is available, either because it
+ was dropped during transmission by some intermediary or because the encoder
+ chose not to transmit it.
+Any Opus frame in any mode MAY have a length of 0.
+</t>
+
+<t>
+The maximum representable length is 255*4+255=1275&nbsp;bytes.
+For 20&nbsp;ms frames, this represents a bitrate of 510&nbsp;kb/s, which is
+ approximately the highest useful rate for lossily compressed fullband stereo
+ music.
+Beyond this point, lossless codecs are more appropriate.
+It is also roughly the maximum useful rate of the MDCT layer, as shortly
+ thereafter quality no longer improves with additional bits due to limitations
+ on the codebook sizes.
+</t>
+
+<t anchor="R2">
+No length is transmitted for the last frame in a VBR packet, or for any of the
+ frames in a CBR packet, as it can be inferred from the total size of the
+ packet and the size of all other data in the packet.
+However, the length of any individual frame MUST NOT exceed
+ 1275&nbsp;bytes&nbsp;[R2], to allow for repacketization by gateways,
+ conference bridges, or other software.
+</t>
+</section>
+
+<section title="Code 0: One Frame in the Packet">
+
+<t>
+For code&nbsp;0 packets, the TOC byte is immediately followed by N-1&nbsp;bytes
+ of compressed data for a single frame (where N is the size of the packet),
+ as illustrated in <xref target="code0_packet"/>.
+</t>
+<figure anchor="code0_packet" title="A Code 0 Packet" align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|0|0|                                               |
++-+-+-+-+-+-+-+-+                                               |
+|                    Compressed frame 1 (N-1 bytes)...          :
+:                                                               |
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+</section>
+
+<section title="Code 1: Two Frames in the Packet, Each with Equal Compressed Size">
+<t anchor="R3">
+For code 1 packets, the TOC byte is immediately followed by the
+ (N-1)/2&nbsp;bytes of compressed data for the first frame, followed by
+ (N-1)/2&nbsp;bytes of compressed data for the second frame, as illustrated in
+ <xref target="code1_packet"/>.
+The number of payload bytes available for compressed data, N-1, MUST be even
+ for all code 1 packets&nbsp;[R3].
+</t>
+<figure anchor="code1_packet" title="A Code 1 Packet" align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|0|1|                                               |
++-+-+-+-+-+-+-+-+                                               :
+|             Compressed frame 1 ((N-1)/2 bytes)...             |
+:                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                               |                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               :
+|             Compressed frame 2 ((N-1)/2 bytes)...             |
+:                                               +-+-+-+-+-+-+-+-+
+|                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+</section>
+
+<section title="Code 2: Two Frames in the Packet, with Different Compressed Sizes">
+<t anchor="R4">
+For code 2 packets, the TOC byte is followed by a one- or two-byte sequence
+ indicating the length of the first frame (marked N1 in <xref target='code2_packet'/>),
+ followed by N1 bytes of compressed data for the first frame.
+The remaining N-N1-2 or N-N1-3&nbsp;bytes are the compressed data for the
+ second frame.
+This is illustrated in <xref target="code2_packet"/>.
+A code 2 packet MUST contain enough bytes to represent a valid length.
+For example, a 1-byte code 2 packet is always invalid, and a 2-byte code 2
+ packet whose second byte is in the range 252...255 is also invalid.
+The length of the first frame, N1, MUST also be no larger than the size of the
+ payload remaining after decoding that length for all code 2 packets&nbsp;[R4].
+This makes, for example, a 2-byte code 2 packet with a second byte in the range
+ 1...251 invalid as well (the only valid 2-byte code 2 packet is one where the
+ length of both frames is zero).
+</t>
+<figure anchor="code2_packet" title="A Code 2 Packet" align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|1|0| N1 (1-2 bytes):                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               :
+|               Compressed frame 1 (N1 bytes)...                |
+:                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                               |                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
+|                     Compressed frame 2...                     :
+:                                                               |
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+</section>
+
+<section title="Code 3: A Signaled Number of Frames in the Packet">
+<t anchor="R5">
+Code 3 packets signal the number of frames, as well as additional
+ padding, called "Opus padding" to indicate that this padding is added at the
+ Opus layer, rather than at the transport layer.
+Code 3 packets MUST have at least 2 bytes&nbsp;[R6,R7].
+The TOC byte is followed by a byte encoding the number of frames in the packet
+ in bits 2 to 7 (marked "M" in <xref target='frame_count_byte'/>), with bit 1 indicating whether
+ or not Opus padding is inserted (marked "p" in <xref target='frame_count_byte'/>), and bit 0
+ indicating VBR (marked "v" in <xref target='frame_count_byte'/>).
+M MUST NOT be zero, and the audio duration contained within a packet MUST NOT
+ exceed 120&nbsp;ms&nbsp;[R5].
+This limits the maximum frame count for any frame size to 48 (for 2.5&nbsp;ms
+ frames), with lower limits for longer frame sizes.
+<xref target="frame_count_byte"/> illustrates the layout of the frame count
+ byte.
+</t>
+<figure anchor="frame_count_byte" title="The frame count byte">
+<artwork align="center"><![CDATA[
+ 0
+ 0 1 2 3 4 5 6 7
++-+-+-+-+-+-+-+-+
+|v|p|     M     |
++-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+<t>
+When Opus padding is used, the number of bytes of padding is encoded in the
+ bytes following the frame count byte.
+Values from 0...254 indicate that 0...254&nbsp;bytes of padding are included,
+ in addition to the byte(s) used to indicate the size of the padding.
+If the value is 255, then the size of the additional padding is 254&nbsp;bytes,
+ plus the padding value encoded in the next byte.
+There MUST be at least one more byte in the packet in this case&nbsp;[R6,R7].
+The additional padding bytes appear at the end of the packet, and MUST be set
+ to zero by the encoder to avoid creating a covert channel.
+The decoder MUST accept any value for the padding bytes, however.
+</t>
+<t>
+Although this encoding provides multiple ways to indicate a given number of
+ padding bytes, each uses a different number of bytes to indicate the padding
+ size, and thus will increase the total packet size by a different amount.
+For example, to add 255 bytes to a packet, set the padding bit, p, to 1, insert
+ a single byte after the frame count byte with a value of 254, and append 254
+ padding bytes with the value zero to the end of the packet.
+To add 256 bytes to a packet, set the padding bit to 1, insert two bytes after
+ the frame count byte with the values 255 and 0, respectively, and append 254
+ padding bytes with the value zero to the end of the packet.
+By using the value 255 multiple times, it is possible to create a packet of any
+ specific, desired size.
+Let P be the number of header bytes used to indicate the padding size plus the
+ number of padding bytes themselves (i.e., P is the total number of bytes added
+ to the packet).
+Then P MUST be no more than N-2&nbsp;[R6,R7].
+</t>
+<t anchor="R6">
+In the CBR case, let R=N-2-P be the number of bytes remaining in the packet
+ after subtracting the (optional) padding.
+Then the compressed length of each frame in bytes is equal to R/M.
+The value R MUST be a non-negative integer multiple of M&nbsp;[R6].
+The compressed data for all M frames follows, each of size
+ R/M&nbsp;bytes, as illustrated in <xref target="code3cbr_packet"/>.
+</t>
+
+<figure anchor="code3cbr_packet" title="A CBR Code 3 Packet" align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|1|1|0|p|     M     |  Padding length (Optional)    :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 1 (R/M bytes)...               :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 2 (R/M bytes)...               :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                              ...                              :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame M (R/M bytes)...               :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:                  Opus Padding (Optional)...                   |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t anchor="R7">
+In the VBR case, the (optional) padding length is followed by M-1 frame
+ lengths (indicated by "N1" to "N[M-1]" in <xref target='code3vbr_packet'/>), each encoded in a
+ one- or two-byte sequence as described above.
+The packet MUST contain enough data for the M-1 lengths after removing the
+ (optional) padding, and the sum of these lengths MUST be no larger than the
+ number of bytes remaining in the packet after decoding them&nbsp;[R7].
+The compressed data for all M frames follows, each frame consisting of the
+ indicated number of bytes, with the final frame consuming any remaining bytes
+ before the final padding, as illustrated in <xref target="code3cbr_packet"/>.
+The number of header bytes (TOC byte, frame count byte, padding length bytes,
+ and frame length bytes), plus the signaled length of the first M-1 frames themselves,
+ plus the signaled length of the padding MUST be no larger than N, the total size of the
+ packet.
+</t>
+
+<figure anchor="code3vbr_packet" title="A VBR Code 3 Packet" align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|1|1|1|p|     M     | Padding length (Optional)     :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+: N1 (1-2 bytes): N2 (1-2 bytes):     ...       :     N[M-1]    |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 1 (N1 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 2 (N2 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                              ...                              :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                     Compressed frame M...                     :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:                  Opus Padding (Optional)...                   |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+</section>
+</section>
+
+<section anchor="examples" title="Examples">
+<t>
+Simplest case, one NB mono 20&nbsp;ms SILK frame:
+</t>
+
+<figure anchor='framing_example_1'>
+<artwork><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|    1    |0|0|0|               compressed data...              :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+Two FB mono 5&nbsp;ms CELT frames of the same compressed size:
+</t>
+
+<figure anchor='framing_example_2'>
+<artwork><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|   29    |0|0|1|               compressed data...              :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+Two FB mono 20&nbsp;ms Hybrid frames of different compressed size:
+</t>
+
+<figure anchor='framing_example_3'>
+<artwork><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|   15    |0|1|1|1|0|     2     |      N1       |               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+               |
+|                       compressed data...                      :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+Four FB stereo 20&nbsp;ms CELT frames of the same compressed size:
+</t>
+
+<figure anchor='framing_example_4'>
+<artwork><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|   31    |1|1|1|0|0|     4     |      compressed data...       :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+</section>
+
+<section anchor="malformed-packets" title="Receiving Malformed Packets">
+<t>
+A receiver MUST NOT process packets which violate any of the rules above as
+ normal Opus packets.
+They are reserved for future applications, such as in-band headers (containing
+ metadata, etc.).
+Packets which violate these constraints may cause implementations of
+ <spanx style="emph">this</spanx> specification to treat them as malformed, and
+ discard them.
+</t>
+<t>
+These constraints are summarized here for reference:
+<list style="format [R%d]">
+<t>Packets are at least one byte.</t>
+<t>No implicit frame length is larger than 1275 bytes.</t>
+<t>Code 1 packets have an odd total length, N, so that (N-1)/2 is an
+ integer.</t>
+<t>Code 2 packets have enough bytes after the TOC for a valid frame
+ length, and that length is no larger than the number of bytes remaining in the
+ packet.</t>
+<t>Code 3 packets contain at least one frame, but no more than 120&nbsp;ms
+ of audio total.</t>
+<t>The length of a CBR code 3 packet, N, is at least two bytes, the number of
+ bytes added to indicate the padding size plus the trailing padding bytes
+ themselves, P, is no more than N-2, and the frame count, M, satisfies
+ the constraint that (N-2-P) is a non-negative integer multiple of M.</t>
+<t>VBR code 3 packets are large enough to contain all the header bytes (TOC
+ byte, frame count byte, any padding length bytes, and any frame length bytes),
+ plus the length of the first M-1 frames, plus any trailing padding bytes.</t>
+</list>
+</t>
+</section>
+
+</section>
+
+<section title="Opus Decoder">
+<t>
+The Opus decoder consists of two main blocks: the SILK decoder and the CELT
+ decoder.
+At any given time, one or both of the SILK and CELT decoders may be active.
+The output of the Opus decode is the sum of the outputs from the SILK and CELT
+ decoders with proper sample rate conversion and delay compensation on the SILK
+ side, and optional decimation (when decoding to sample rates less than
+ 48&nbsp;kHz) on the CELT side, as illustrated in the block diagram below.
+</t>
+<figure>
+<artwork>
+<![CDATA[
+                         +---------+    +------------+
+                         |  SILK   |    |   Sample   |
+                      +->| Decoder |--->|    Rate    |----+
+Bit-    +---------+   |  |         |    | Conversion |    v
+stream  |  Range  |---+  +---------+    +------------+  /---\  Audio
+------->| Decoder |                                     | + |------>
+        |         |---+  +---------+    +------------+  \---/
+        +---------+   |  |  CELT   |    | Decimation |    ^
+                      +->| Decoder |--->| (Optional) |----+
+                         |         |    |            |
+                         +---------+    +------------+
+]]>
+</artwork>
+</figure>
+
+<section anchor="range-decoder" title="Range Decoder">
+<t>
+Opus uses an entropy coder based on range coding <xref target="range-coding"></xref>
+<xref target="Martin79"></xref>,
+which is itself a rediscovery of the FIFO arithmetic code introduced by <xref target="coding-thesis"></xref>.
+It is very similar to arithmetic encoding, except that encoding is done with
+digits in any base instead of with bits,
+so it is faster when using larger bases (i.e., a byte). All of the
+calculations in the range coder must use bit-exact integer arithmetic.
+</t>
+<t>
+Symbols may also be coded as "raw bits" packed directly into the bitstream,
+ bypassing the range coder.
+These are packed backwards starting at the end of the frame, as illustrated in
+ <xref target="rawbits-example"/>.
+This reduces complexity and makes the stream more resilient to bit errors, as
+ corruption in the raw bits will not desynchronize the decoding process, unlike
+ corruption in the input to the range decoder.
+Raw bits are only used in the CELT layer.
+</t>
+
+<figure anchor="rawbits-example" title="Illustrative example of packing range
+ coder and raw bits data">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| Range coder data (packed MSB to LSB) ->                       :
++                                                               +
+:                                                               :
++     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:     | <- Boundary occurs at an arbitrary bit position         :
++-+-+-+                                                         +
+:                          <- Raw bits data (packed LSB to MSB) |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<t>
+Each symbol coded by the range coder is drawn from a finite alphabet and coded
+ in a separate "context", which describes the size of the alphabet and the
+ relative frequency of each symbol in that alphabet.
+</t>
+<t>
+Suppose there is a context with n symbols, identified with an index that ranges
+ from 0 to n-1.
+The parameters needed to encode or decode symbol k in this context are
+ represented by a three-tuple (fl[k],&nbsp;fh[k],&nbsp;ft), with
+ 0&nbsp;&lt;=&nbsp;fl[k]&nbsp;&lt;&nbsp;fh[k]&nbsp;&lt;=&nbsp;ft&nbsp;&lt;=&nbsp;65535.
+The values of this tuple are derived from the probability model for the
+ symbol, represented by traditional "frequency counts".
+Because Opus uses static contexts these are not updated as symbols are decoded.
+Let f[i] be the frequency of symbol i.
+Then the three-tuple corresponding to symbol k is given by
+</t>
+<figure align="center">
+<artwork align="center"><![CDATA[
+        k-1                                   n-1
+        __                                    __
+fl[k] = \  f[i],  fh[k] = fl[k] + f[k],  ft = \  f[i]
+        /_                                    /_
+        i=0                                   i=0
+]]></artwork>
+</figure>
+<t>
+The range decoder extracts the symbols and integers encoded using the range
+ encoder in <xref target="range-encoder"/>.
+The range decoder maintains an internal state vector composed of the two-tuple
+ (val,&nbsp;rng), representing the difference between the high end of the
+ current range and the actual coded value, minus one, and the size of the
+ current range, respectively.
+Both val and rng are 32-bit unsigned integer values.
+</t>
+
+<section anchor="range-decoder-init" title="Range Decoder Initialization">
+<t>
+Let b0 be the first input byte (or zero if there are no bytes in this Opus
+ frame).
+The decoder initializes rng to 128 and initializes val to
+ (127&nbsp;-&nbsp;(b0&gt;&gt;1)), where (b0&gt;&gt;1) is the top 7 bits of the
+ first input byte.
+It saves the remaining bit, (b0&amp;1), for use in the renormalization
+ procedure described in <xref target="range-decoder-renorm"/>, which the
+ decoder invokes immediately after initialization to read additional bits and
+ establish the invariant that rng&nbsp;&gt;&nbsp;2**23.
+</t>
+</section>
+
+<section anchor="decoding-symbols" title="Decoding Symbols">
+<t>
+Decoding a symbol is a two-step process.
+The first step determines a 16-bit unsigned value fs, which lies within the
+ range of some symbol in the current context.
+The second step updates the range decoder state with the three-tuple
+ (fl[k],&nbsp;fh[k],&nbsp;ft) corresponding to that symbol.
+</t>
+<t>
+The first step is implemented by ec_decode() (entdec.c), which computes
+<figure align="center">
+<artwork align="center"><![CDATA[
+               val
+fs = ft - min(------ + 1, ft) .
+              rng/ft
+]]></artwork>
+</figure>
+The divisions here are integer division.
+</t>
+<t>
+The decoder then identifies the symbol in the current context corresponding to
+ fs; i.e., the value of k whose three-tuple (fl[k],&nbsp;fh[k],&nbsp;ft)
+ satisfies fl[k]&nbsp;&lt;=&nbsp;fs&nbsp;&lt;&nbsp;fh[k].
+It uses this tuple to update val according to
+<figure align="center">
+<artwork align="center"><![CDATA[
+            rng
+val = val - --- * (ft - fh[k]) .
+            ft
+]]></artwork>
+</figure>
+If fl[k] is greater than zero, then the decoder updates rng using
+<figure align="center">
+<artwork align="center"><![CDATA[
+      rng
+rng = --- * (fh[k] - fl[k]) .
+      ft
+]]></artwork>
+</figure>
+Otherwise, it updates rng using
+<figure align="center">
+<artwork align="center"><![CDATA[
+            rng
+rng = rng - --- * (ft - fh[k]) .
+            ft
+]]></artwork>
+</figure>
+</t>
+<t>
+Using a special case for the first symbol (rather than the last symbol, as is
+ commonly done in other arithmetic coders) ensures that all the truncation
+ error from the finite precision arithmetic accumulates in symbol 0.
+This makes the cost of coding a 0 slightly smaller, on average, than its
+ estimated probability indicates and makes the cost of coding any other symbol
+ slightly larger.
+When contexts are designed so that 0 is the most probable symbol, which is
+ often the case, this strategy minimizes the inefficiency introduced by the
+ finite precision.
+It also makes some of the special-case decoding routines in
+ <xref target="decoding-alternate"/> particularly simple.
+</t>
+<t>
+After the updates, implemented by ec_dec_update() (entdec.c), the decoder
+ normalizes the range using the procedure in the next section, and returns the
+ index k.
+</t>
+
+<section anchor="range-decoder-renorm" title="Renormalization">
+<t>
+To normalize the range, the decoder repeats the following process, implemented
+ by ec_dec_normalize() (entdec.c), until rng&nbsp;&gt;&nbsp;2**23.
+If rng is already greater than 2**23, the entire process is skipped.
+First, it sets rng to (rng&lt;&lt;8).
+Then it reads the next byte of the Opus frame and forms an 8-bit value sym,
+ using the left-over bit buffered from the previous byte as the high bit
+ and the top 7 bits of the byte just read as the other 7 bits of sym.
+The remaining bit in the byte just read is buffered for use in the next
+ iteration.
+If no more input bytes remain, it uses zero bits instead.
+See <xref target="range-decoder-init"/> for the initialization used to process
+ the first byte.
+Then, it sets
+<figure align="center">
+<artwork align="center"><![CDATA[
+val = ((val<<8) + (255-sym)) & 0x7FFFFFFF .
+]]></artwork>
+</figure>
+</t>
+<t>
+It is normal and expected that the range decoder will read several bytes
+ into the raw bits data (if any) at the end of the packet by the time the frame
+ is completely decoded, as illustrated in <xref target="finalize-example"/>.
+This same data MUST also be returned as raw bits when requested.
+The encoder is expected to terminate the stream in such a way that the decoder
+ will decode the intended values regardless of the data contained in the raw
+ bits.
+<xref target="encoder-finalizing"/> describes a procedure for doing this.
+If the range decoder consumes all of the bytes belonging to the current frame,
+ it MUST continue to use zero when any further input bytes are required, even
+ if there is additional data in the current packet from padding or other
+ frames.
+</t>
+
+<figure anchor="finalize-example" title="Illustrative example of raw bits
+ overlapping range coder data">
+<artwork align="center"><![CDATA[
+ n              n+1             n+2             n+3
+ 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:     | <----------- Overlap region ------------> |             :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+      ^                                           ^
+      |   End of data buffered by the range coder |
+...-----------------------------------------------+
+      |
+      | End of data consumed by raw bits
+      +-------------------------------------------------------...
+]]></artwork>
+</figure>
+</section>
+</section>
+
+<section anchor="decoding-alternate" title="Alternate Decoding Methods">
+<t>
+The reference implementation uses three additional decoding methods that are
+ exactly equivalent to the above, but make assumptions and simplifications that
+ allow for a more efficient implementation.
+</t>
+<section anchor="ec_decode_bin" title="ec_decode_bin()">
+<t>
+The first is ec_decode_bin() (entdec.c), defined using the parameter ftb
+ instead of ft.
+It is mathematically equivalent to calling ec_decode() with
+ ft&nbsp;=&nbsp;(1&lt;&lt;ftb), but avoids one of the divisions.
+</t>
+</section>
+<section anchor="ec_dec_bit_logp" title="ec_dec_bit_logp()">
+<t>
+The next is ec_dec_bit_logp() (entdec.c), which decodes a single binary symbol,
+ replacing both the ec_decode() and ec_dec_update() steps.
+The context is described by a single parameter, logp, which is the absolute
+ value of the base-2 logarithm of the probability of a "1".
+It is mathematically equivalent to calling ec_decode() with
+ ft&nbsp;=&nbsp;(1&lt;&lt;logp), followed by ec_dec_update() with
+ the 3-tuple (fl[k]&nbsp;=&nbsp;0,
+ fh[k]&nbsp;=&nbsp;(1&lt;&lt;logp)&nbsp;-&nbsp;1,
+ ft&nbsp;=&nbsp;(1&lt;&lt;logp)) if the returned value
+ of fs is less than (1&lt;&lt;logp)&nbsp;-&nbsp;1 (a "0" was decoded), and with
+ (fl[k]&nbsp;=&nbsp;(1&lt;&lt;logp)&nbsp;-&nbsp;1,
+ fh[k]&nbsp;=&nbsp;ft&nbsp;=&nbsp;(1&lt;&lt;logp)) otherwise (a "1" was
+ decoded).
+The implementation requires no multiplications or divisions.
+</t>
+</section>
+<section anchor="ec_dec_icdf" title="ec_dec_icdf()">
+<t>
+The last is ec_dec_icdf() (entdec.c), which decodes a single symbol with a
+ table-based context of up to 8 bits, also replacing both the ec_decode() and
+ ec_dec_update() steps, as well as the search for the decoded symbol in between.
+The context is described by two parameters, an icdf
+ ("inverse" cumulative distribution function) table and ftb.
+As with ec_decode_bin(), (1&lt;&lt;ftb) is equivalent to ft.
+idcf[k], on the other hand, stores (1&lt;&lt;ftb)-fh[k], which is equal to
+ (1&lt;&lt;ftb)&nbsp;-&nbsp;fl[k+1].
+fl[0] is assumed to be 0, and the table is terminated by a value of 0 (where
+ fh[k]&nbsp;==&nbsp;ft).
+</t>
+<t>
+The function is mathematically equivalent to calling ec_decode() with
+ ft&nbsp;=&nbsp;(1&lt;&lt;ftb), using the returned value fs to search the table
+ for the first entry where fs&nbsp;&lt;&nbsp;(1&lt;&lt;ftb)-icdf[k], and
+ calling ec_dec_update() with
+ fl[k]&nbsp;=&nbsp;(1&lt;&lt;ftb)&nbsp;-&nbsp;icdf[k-1] (or 0
+ if k&nbsp;==&nbsp;0), fh[k]&nbsp;=&nbsp;(1&lt;&lt;ftb)&nbsp;-&nbsp;idcf[k],
+ and ft&nbsp;=&nbsp;(1&lt;&lt;ftb).
+Combining the search with the update allows the division to be replaced by a
+ series of multiplications (which are usually much cheaper), and using an
+ inverse CDF allows the use of an ftb as large as 8 in an 8-bit table without
+ any special cases.
+This is the primary interface with the range decoder in the SILK layer, though
+ it is used in a few places in the CELT layer as well.
+</t>
+<t>
+Although icdf[k] is more convenient for the code, the frequency counts, f[k],
+ are a more natural representation of the probability distribution function
+ (PDF) for a given symbol.
+Therefore this draft lists the latter, not the former, when describing the
+ context in which a symbol is coded as a list, e.g., {4, 4, 4, 4}/16 for a
+ uniform context with four possible values and ft&nbsp;=&nbsp;16.
+The value of ft after the slash is always the sum of the entries in the PDF,
+ but is included for convenience.
+Contexts with identical probabilities, f[k]/ft, but different values of ft
+ (or equivalently, ftb) are not the same, and cannot, in general, be used in
+ place of one another.
+An icdf table is also not capable of representing a PDF where the first symbol
+ has 0 probability.
+In such contexts, ec_dec_icdf() can decode the symbol by using a table that
+ drops the entries for any initial zero-probability values and adding the
+ constant offset of the first value with a non-zero probability to its return
+ value.
+</t>
+</section>
+</section>
+
+<section anchor="decoding-bits" title="Decoding Raw Bits">
+<t>
+The raw bits used by the CELT layer are packed at the end of the packet, with
+ the least significant bit of the first value packed in the least significant
+ bit of the last byte, filling up to the most significant bit in the last byte,
+ continuing on to the least significant bit of the penultimate byte, and so on.
+The reference implementation reads them using ec_dec_bits() (entdec.c).
+Because the range decoder must read several bytes ahead in the stream, as
+ described in <xref target="range-decoder-renorm"/>, the input consumed by the
+ raw bits may overlap with the input consumed by the range coder, and a decoder
+ MUST allow this.
+The format should render it impossible to attempt to read more raw bits than
+ there are actual bits in the frame, though a decoder may wish to check for
+ this and report an error.
+</t>
+</section>
+
+<section anchor="ec_dec_uint" title="Decoding Uniformly Distributed Integers">
+<t>
+The function ec_dec_uint() (entdec.c) decodes one of ft equiprobable values in
+ the range 0 to (ft&nbsp;-&nbsp;1), inclusive, each with a frequency of 1,
+ where ft may be as large as (2**32&nbsp;-&nbsp;1).
+Because ec_decode() is limited to a total frequency of (2**16&nbsp;-&nbsp;1),
+ it splits up the value into a range coded symbol representing up to 8 of the
+ high bits, and, if necessary, raw bits representing the remainder of the
+ value.
+The limit of 8 bits in the range coded symbol is a trade-off between
+ implementation complexity, modeling error (since the symbols no longer truly
+ have equal coding cost), and rounding error introduced by the range coder
+ itself (which gets larger as more bits are included).
+Using raw bits reduces the maximum number of divisions required in the worst
+ case, but means that it may be possible to decode a value outside the range
+ 0 to (ft&nbsp;-&nbsp;1), inclusive.
+</t>
+
+<t>
+ec_dec_uint() takes a single, positive parameter, ft, which is not necessarily
+ a power of two, and returns an integer, t, whose value lies between 0 and
+ (ft&nbsp;-&nbsp;1), inclusive.
+Let ftb&nbsp;=&nbsp;ilog(ft&nbsp;-&nbsp;1), i.e., the number of bits required
+ to store (ft&nbsp;-&nbsp;1) in two's complement notation.
+If ftb is 8 or less, then t is decoded with t&nbsp;=&nbsp;ec_decode(ft), and
+ the range coder state is updated using the three-tuple (t, t&nbsp;+&nbsp;1,
+ ft).
+</t>
+<t>
+If ftb is greater than 8, then the top 8 bits of t are decoded using
+<figure align="center">
+<artwork align="center"><![CDATA[
+t = ec_decode(((ft - 1) >> (ftb - 8)) + 1) ,
+]]></artwork>
+</figure>
+ the decoder state is updated using the three-tuple
+ (t, t&nbsp;+&nbsp;1,
+ ((ft&nbsp;-&nbsp;1)&nbsp;&gt;&gt;&nbsp;(ftb&nbsp;-&nbsp;8))&nbsp;+&nbsp;1),
+ and the remaining bits are decoded as raw bits, setting
+<figure align="center">
+<artwork align="center"><![CDATA[
+t = (t << (ftb - 8)) | ec_dec_bits(ftb - 8) .
+]]></artwork>
+</figure>
+If, at this point, t >= ft, then the current frame is corrupt.
+In that case, the decoder should assume there has been an error in the coding,
+ decoding, or transmission and SHOULD take measures to conceal the
+ error and/or report to the application that the error has occurred.
+</t>
+
+</section>
+
+<section anchor="decoder-tell" title="Current Bit Usage">
+<t>
+The bit allocation routines in the CELT decoder need a conservative upper bound
+ on the number of bits that have been used from the current frame thus far,
+ including both range coder bits and raw bits.
+This drives allocation decisions that must match those made in the encoder.
+The upper bound is computed in the reference implementation to whole-bit
+ precision by the function ec_tell() (entcode.h) and to fractional 1/8th bit
+ precision by the function ec_tell_frac() (entcode.c).
+Like all operations in the range coder, it must be implemented in a bit-exact
+ manner, and must produce exactly the same value returned by the same functions
+ in the encoder after encoding the same symbols.
+</t>
+<t>
+ec_tell() is guaranteed to return ceil(ec_tell_frac()/8.0).
+In various places the codec will check to ensure there is enough room to
+ contain a symbol before attempting to decode it.
+In practice, although the number of bits used so far is an upper bound,
+ decoding a symbol whose probability model suggests it has a worst-case cost of
+ p 1/8th bits may actually advance the return value of ec_tell_frac() by
+ p-1, p, or p+1 1/8th bits, due to approximation error in that upper bound,
+ truncation error in the range coder, and for large values of ft, modeling
+ error in ec_dec_uint().
+</t>
+<t>
+However, this error is bounded, and periodic calls to ec_tell() or
+ ec_tell_frac() at precisely defined points in the decoding process prevent it
+ from accumulating.
+For a range coder symbol that requires a whole number of bits (i.e.,
+ for which ft/(fh[k]&nbsp;-&nbsp;fl[k]) is a power of two), where there are at
+ least p 1/8th bits available, decoding the symbol will never cause ec_tell() or
+ ec_tell_frac() to exceed the size of the frame ("bust the budget").
+In this case the return value of ec_tell_frac() will only advance by more than
+ p 1/8th bits if there was an additional, fractional number of bits remaining,
+ and it will never advance beyond the next whole-bit boundary, which is safe,
+ since frames always contain a whole number of bits.
+However, when p is not a whole number of bits, an extra 1/8th bit is required
+ to ensure that decoding the symbol will not bust the budget.
+</t>
+<t>
+The reference implementation keeps track of the total number of whole bits that
+ have been processed by the decoder so far in the variable nbits_total,
+ including the (possibly fractional) number of bits that are currently
+ buffered, but not consumed, inside the range coder.
+nbits_total is initialized to 9 just before the initial range renormalization
+ process completes (or equivalently, it can be initialized to 33 after the
+ first renormalization).
+The extra two bits over the actual amount buffered by the range coder
+ guarantees that it is an upper bound and that there is enough room for the
+ encoder to terminate the stream.
+Each iteration through the range coder's renormalization loop increases
+ nbits_total by 8.
+Reading raw bits increases nbits_total by the number of raw bits read.
+</t>
+
+<section anchor="ec_tell" title="ec_tell()">
+<t>
+The whole number of bits buffered in rng may be estimated via lg = ilog(rng).
+ec_tell() then becomes a simple matter of removing these bits from the total.
+It returns (nbits_total - lg).
+</t>
+<t>
+In a newly initialized decoder, before any symbols have been read, this reports
+ that 1 bit has been used.
+This is the bit reserved for termination of the encoder.
+</t>
+</section>
+
+<section anchor="ec_tell_frac" title="ec_tell_frac()">
+<t>
+ec_tell_frac() estimates the number of bits buffered in rng to fractional
+ precision.
+Since rng must be greater than 2**23 after renormalization, lg must be at least
+ 24.
+Let
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+r_Q15 = rng >> (lg-16) ,
+]]></artwork>
+</figure>
+ so that 32768 &lt;= r_Q15 &lt; 65536, an unsigned Q15 value representing the
+ fractional part of rng.
+Then the following procedure can be used to add one bit of precision to lg.
+First, update
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+r_Q15 = (r_Q15*r_Q15) >> 15 .
+]]></artwork>
+</figure>
+Then add the 16th bit of r_Q15 to lg via
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+lg = 2*lg + (r_Q15 >> 16) .
+]]></artwork>
+</figure>
+Finally, if this bit was a 1, reduce r_Q15 by a factor of two via
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+r_Q15 = r_Q15 >> 1 ,
+]]></artwork>
+</figure>
+ so that it once again lies in the range 32768 &lt;= r_Q15 &lt; 65536.
+</t>
+<t>
+This procedure is repeated three times to extend lg to 1/8th bit precision.
+ec_tell_frac() then returns (nbits_total*8 - lg).
+</t>
+</section>
+
+</section>
+
+</section>
+
+<section anchor="silk_decoder_outline" title="SILK Decoder">
+<t>
+The decoder's LP layer uses a modified version of the SILK codec (herein simply
+ called "SILK"), which runs a decoded excitation signal through adaptive
+ long-term and short-term prediction synthesis filters.
+It runs at NB, MB, and WB sample rates internally.
+When used in a SWB or FB Hybrid frame, the LP layer itself still only runs in
+ WB.
+</t>
+
+<section title="SILK Decoder Modules">
+<t>
+An overview of the decoder is given in <xref target="silk_decoder_figure"/>.
+</t>
+<figure align="center" anchor="silk_decoder_figure" title="SILK Decoder">
+<artwork align="center">
+<![CDATA[
+   +---------+    +------------+
+-->| Range   |--->| Decode     |---------------------------+
+ 1 | Decoder | 2  | Parameters |----------+       5        |
+   +---------+    +------------+     4    |                |
+                       3 |                |                |
+                        \/               \/               \/
+                  +------------+   +------------+   +------------+
+                  | Generate   |-->| LTP        |-->| LPC        |
+                  | Excitation |   | Synthesis  |   | Synthesis  |
+                  +------------+   +------------+   +------------+
+                                          ^                |
+                                          |                |
+                      +-------------------+----------------+
+                      |                                      6
+                      |   +------------+   +-------------+
+                      +-->| Stereo     |-->| Sample Rate |-->
+                          | Unmixing   | 7 | Conversion  | 8
+                          +------------+   +-------------+
+
+1: Range encoded bitstream
+2: Coded parameters
+3: Pulses, LSBs, and signs
+4: Pitch lags, Long-Term Prediction (LTP) coefficients
+5: Linear Predictive Coding (LPC) coefficients and gains
+6: Decoded signal (mono or mid-side stereo)
+7: Unmixed signal (mono or left-right stereo)
+8: Resampled signal
+]]>
+</artwork>
+</figure>
+
+<t>
+The decoder feeds the bitstream (1) to the range decoder from
+ <xref target="range-decoder"/>, and then decodes the parameters in it (2)
+ using the procedures detailed in
+ Sections&nbsp;<xref format="counter" target="silk_header_bits"/>
+ through&nbsp;<xref format="counter" target="silk_signs"/>.
+These parameters (3, 4, 5) are used to generate an excitation signal (see
+ <xref target="silk_excitation_reconstruction"/>), which is fed to an optional
+ long-term prediction (LTP) filter (voiced frames only, see
+ <xref target="silk_ltp_synthesis"/>) and then a short-term prediction filter
+ (see <xref target="silk_lpc_synthesis"/>), producing the decoded signal (6).
+For stereo streams, the mid-side representation is converted to separate left
+ and right channels (7).
+The result is finally resampled to the desired output sample rate (e.g.,
+ 48&nbsp;kHz) so that the resampled signal (8) can be mixed with the CELT
+ layer.
+</t>
+
+</section>
+
+<section anchor="silk_layer_organization" title="LP Layer Organization">
+
+<t>
+Internally, the LP layer of a single Opus frame is composed of either a single
+ 10&nbsp;ms regular SILK frame or between one and three 20&nbsp;ms regular SILK
+ frames.
+A stereo Opus frame may double the number of regular SILK frames (up to a total
+ of six), since it includes separate frames for a mid channel and, optionally,
+ a side channel.
+Optional Low Bit-Rate Redundancy (LBRR) frames, which are reduced-bitrate
+ encodings of previous SILK frames, may be included to aid in recovery from
+ packet loss.
+If present, these appear before the regular SILK frames.
+They are in most respects identical to regular, active SILK frames, except that
+ they are usually encoded with a lower bitrate.
+This draft uses "SILK frame" to refer to either one and "regular SILK frame" if
+ it needs to draw a distinction between the two.
+</t>
+<t>
+Logically, each SILK frame is in turn composed of either two or four 5&nbsp;ms
+ subframes.
+Various parameters, such as the quantization gain of the excitation and the
+ pitch lag and filter coefficients can vary on a subframe-by-subframe basis.
+Physically, the parameters for each subframe are interleaved in the bitstream,
+ as described in the relevant sections for each parameter.
+</t>
+<t>
+All of these frames and subframes are decoded from the same range coder, with
+ no padding between them.
+Thus packing multiple SILK frames in a single Opus frame saves, on average,
+ half a byte per SILK frame.
+It also allows some parameters to be predicted from prior SILK frames in the
+ same Opus frame, since this does not degrade packet loss robustness (beyond
+ any penalty for merely using fewer, larger packets to store multiple frames).
+</t>
+
+<t>
+Stereo support in SILK uses a variant of mid-side coding, allowing a mono
+ decoder to simply decode the mid channel.
+However, the data for the two channels is interleaved, so a mono decoder must
+ still unpack the data for the side channel.
+It would be required to do so anyway for Hybrid Opus frames, or to support
+ decoding individual 20&nbsp;ms frames.
+</t>
+
+<t>
+<xref target="silk_symbols"/> summarizes the overall grouping of the contents of
+ the LP layer.
+Figures&nbsp;<xref format="counter" target="silk_mono_60ms_frame"/>
+ and&nbsp;<xref format="counter" target="silk_stereo_60ms_frame"/> illustrate
+ the ordering of the various SILK frames for a 60&nbsp;ms Opus frame, for both
+ mono and stereo, respectively.
+</t>
+
+<texttable anchor="silk_symbols"
+ title="Organization of the SILK layer of an Opus frame">
+<ttcol align="center">Symbol(s)</ttcol>
+<ttcol align="center">PDF(s)</ttcol>
+<ttcol align="center">Condition</ttcol>
+
+<c>Voice Activity Detection (VAD) flags</c>
+<c>{1, 1}/2</c>
+<c/>
+
+<c>LBRR flag</c>
+<c>{1, 1}/2</c>
+<c/>
+
+<c>Per-frame LBRR flags</c>
+<c><xref target="silk_lbrr_flag_pdfs"/></c>
+<c><xref target="silk_lbrr_flags"/></c>
+
+<c>LBRR Frame(s)</c>
+<c><xref target="silk_frame"/></c>
+<c><xref target="silk_lbrr_flags"/></c>
+
+<c>Regular SILK Frame(s)</c>
+<c><xref target="silk_frame"/></c>
+<c/>
+
+</texttable>
+
+<figure align="center" anchor="silk_mono_60ms_frame"
+ title="A 60&nbsp;ms Mono Frame">
+<artwork align="center"><![CDATA[
++---------------------------------+
+|            VAD Flags            |
++---------------------------------+
+|            LBRR Flag            |
++---------------------------------+
+| Per-Frame LBRR Flags (Optional) |
++---------------------------------+
+|     LBRR Frame 1 (Optional)     |
++---------------------------------+
+|     LBRR Frame 2 (Optional)     |
++---------------------------------+
+|     LBRR Frame 3 (Optional)     |
++---------------------------------+
+|      Regular SILK Frame 1       |
++---------------------------------+
+|      Regular SILK Frame 2       |
++---------------------------------+
+|      Regular SILK Frame 3       |
++---------------------------------+
+]]></artwork>
+</figure>
+
+<figure align="center" anchor="silk_stereo_60ms_frame"
+ title="A 60&nbsp;ms Stereo Frame">
+<artwork align="center"><![CDATA[
++---------------------------------------+
+|             Mid VAD Flags             |
++---------------------------------------+
+|             Mid LBRR Flag             |
++---------------------------------------+
+|             Side VAD Flags            |
++---------------------------------------+
+|             Side LBRR Flag            |
++---------------------------------------+
+|  Mid Per-Frame LBRR Flags (Optional)  |
++---------------------------------------+
+| Side Per-Frame LBRR Flags (Optional)  |
++---------------------------------------+
+|     Mid LBRR Frame 1 (Optional)       |
++---------------------------------------+
+|     Side LBRR Frame 1 (Optional)      |
++---------------------------------------+
+|     Mid LBRR Frame 2 (Optional)       |
++---------------------------------------+
+|     Side LBRR Frame 2 (Optional)      |
++---------------------------------------+
+|     Mid LBRR Frame 3 (Optional)       |
++---------------------------------------+
+|     Side LBRR Frame 3 (Optional)      |
++---------------------------------------+
+|      Mid Regular SILK Frame 1         |
++---------------------------------------+
+| Side Regular SILK Frame 1 (Optional)  |
++---------------------------------------+
+|      Mid Regular SILK Frame 2         |
++---------------------------------------+
+| Side Regular SILK Frame 2 (Optional)  |
++---------------------------------------+
+|      Mid Regular SILK Frame 3         |
++---------------------------------------+
+| Side Regular SILK Frame 3 (Optional)  |
++---------------------------------------+
+]]></artwork>
+</figure>
+
+</section>
+
+<section anchor="silk_header_bits" title="Header Bits">
+<t>
+The LP layer begins with two to eight header bits, decoded in silk_Decode()
+ (dec_API.c).
+These consist of one Voice Activity Detection (VAD) bit per frame (up to 3),
+ followed by a single flag indicating the presence of LBRR frames.
+For a stereo packet, these first flags correspond to the mid channel, and a
+ second set of flags is included for the side channel.
+</t>
+<t>
+Because these are the first symbols decoded by the range coder and because they
+ are coded as binary values with uniform probability, they can be extracted
+ directly from the most significant bits of the first byte of compressed data.
+Thus, a receiver can determine if an Opus frame contains any active SILK frames
+ without the overhead of using the range decoder.
+</t>
+</section>
+
+<section anchor="silk_lbrr_flags" title="Per-Frame LBRR Flags">
+<t>
+For Opus frames longer than 20&nbsp;ms, a set of LBRR flags is
+ decoded for each channel that has its LBRR flag set.
+Each set contains one flag per 20&nbsp;ms SILK frame.
+40&nbsp;ms Opus frames use the 2-frame LBRR flag PDF from
+ <xref target="silk_lbrr_flag_pdfs"/>, and 60&nbsp;ms Opus frames use the
+ 3-frame LBRR flag PDF.
+For each channel, the resulting 2- or 3-bit integer contains the corresponding
+ LBRR flag for each frame, packed in order from the LSB to the MSB.
+</t>
+
+<texttable anchor="silk_lbrr_flag_pdfs" title="LBRR Flag PDFs">
+<ttcol>Frame Size</ttcol>
+<ttcol>PDF</ttcol>
+<c>40&nbsp;ms</c> <c>{0, 53, 53, 150}/256</c>
+<c>60&nbsp;ms</c> <c>{0, 41, 20, 29, 41, 15, 28, 82}/256</c>
+</texttable>
+
+<t>
+A 10&nbsp;or 20&nbsp;ms Opus frame does not contain any per-frame LBRR flags,
+ as there may be at most one LBRR frame per channel.
+The global LBRR flag in the header bits (see <xref target="silk_header_bits"/>)
+ is already sufficient to indicate the presence of that single LBRR frame.
+</t>
+
+</section>
+
+<section anchor="silk_lbrr_frames" title="LBRR Frames">
+<t>
+The LBRR frames, if present, contain an encoded representation of the signal
+ immediately prior to the current Opus frame as if it were encoded with the
+ current mode, frame size, audio bandwidth, and channel count, even if those
+ differ from the prior Opus frame.
+When one of these parameters changes from one Opus frame to the next, this
+ implies that the LBRR frames of the current Opus frame may not be simple
+ drop-in replacements for the contents of the previous Opus frame.
+</t>
+
+<t>
+For example, when switching from 20&nbsp;ms to 60&nbsp;ms, the 60&nbsp;ms Opus
+ frame may contain LBRR frames covering up to three prior 20&nbsp;ms Opus
+ frames, even if those frames already contained LBRR frames covering some of
+ the same time periods.
+When switching from 20&nbsp;ms to 10&nbsp;ms, the 10&nbsp;ms Opus frame can
+ contain an LBRR frame covering at most half the prior 20&nbsp;ms Opus frame,
+ potentially leaving a hole that needs to be concealed from even a single
+ packet loss (see <xref target="Packet Loss Concealment"/>).
+When switching from mono to stereo, the LBRR frames in the first stereo Opus
+ frame MAY contain a non-trivial side channel.
+</t>
+
+<t>
+In order to properly produce LBRR frames under all conditions, an encoder might
+ need to buffer up to 60&nbsp;ms of audio and re-encode it during these
+ transitions.
+However, the reference implementation opts to disable LBRR frames at the
+ transition point for simplicity.
+Since transitions are relatively infrequent in normal usage, this does not have
+ a significant impact on packet loss robustness.
+</t>
+
+<t>
+The LBRR frames immediately follow the LBRR flags, prior to any regular SILK
+ frames.
+<xref target="silk_frame"/> describes their exact contents.
+LBRR frames do not include their own separate VAD flags.
+LBRR frames are only meant to be transmitted for active speech, thus all LBRR
+ frames are treated as active.
+</t>
+
+<t>
+In a stereo Opus frame longer than 20&nbsp;ms, although the per-frame LBRR
+ flags for the mid channel are coded as a unit before the per-frame LBRR flags
+ for the side channel, the LBRR frames themselves are interleaved.
+The decoder parses an LBRR frame for the mid channel of a given 20&nbsp;ms
+ interval (if present) and then immediately parses the corresponding LBRR
+ frame for the side channel (if present), before proceeding to the next
+ 20&nbsp;ms interval.
+</t>
+</section>
+
+<section anchor="silk_regular_frames" title="Regular SILK Frames">
+<t>
+The regular SILK frame(s) follow the LBRR frames (if any).
+<xref target="silk_frame"/> describes their contents, as well.
+Unlike the LBRR frames, a regular SILK frame is coded for each time interval in
+ an Opus frame, even if the corresponding VAD flags are unset.
+For stereo Opus frames longer than 20&nbsp;ms, the regular mid and side SILK
+ frames for each 20&nbsp;ms interval are interleaved, just as with the LBRR
+ frames.
+The side frame may be skipped by coding an appropriate flag, as detailed in
+ <xref target="silk_mid_only_flag"/>.
+</t>
+</section>
+
+<section anchor="silk_frame" title="SILK Frame Contents">
+<t>
+Each SILK frame includes a set of side information that encodes
+<list style="symbols">
+<t>The frame type and quantization type (<xref target="silk_frame_type"/>),</t>
+<t>Quantization gains (<xref target="silk_gains"/>),</t>
+<t>Short-term prediction filter coefficients (<xref target="silk_nlsfs"/>),</t>
+<t>A Line Spectral Frequencies (LSF) interpolation weight (<xref target="silk_nlsf_interpolation"/>),</t>
+<t>
+Long-term prediction filter lags and gains (<xref target="silk_ltp_params"/>),
+ and
+</t>
+<t>A linear congruential generator (LCG) seed (<xref target="silk_seed"/>).</t>
+</list>
+The quantized excitation signal (see <xref target="silk_excitation"/>) follows
+ these at the end of the frame.
+<xref target="silk_frame_symbols"/> details the overall organization of a
+ SILK frame.
+</t>
+
+<texttable anchor="silk_frame_symbols"
+ title="Order of the symbols in an individual SILK frame">
+<ttcol align="center">Symbol(s)</ttcol>
+<ttcol align="center">PDF(s)</ttcol>
+<ttcol align="center">Condition</ttcol>
+
+<c>Stereo Prediction Weights</c>
+<c><xref target="silk_stereo_pred_pdfs"/></c>
+<c><xref target="silk_stereo_pred"/></c>
+
+<c>Mid-only Flag</c>
+<c><xref target="silk_mid_only_pdf"/></c>
+<c><xref target="silk_mid_only_flag"/></c>
+
+<c>Frame Type</c>
+<c><xref target="silk_frame_type"/></c>
+<c/>
+
+<c>Subframe Gains</c>
+<c><xref target="silk_gains"/></c>
+<c/>
+
+<c>Normalized LSF Stage-1 Index</c>
+<c><xref target="silk_nlsf_stage1_pdfs"/></c>
+<c/>
+
+<c>Normalized LSF Stage-2 Residual</c>
+<c><xref target="silk_nlsf_stage2"/></c>
+<c/>
+
+<c>Normalized LSF Interpolation Weight</c>
+<c><xref target="silk_nlsf_interp_pdf"/></c>
+<c>20&nbsp;ms frame</c>
+
+<c>Primary Pitch Lag</c>
+<c><xref target="silk_ltp_lags"/></c>
+<c>Voiced frame</c>
+
+<c>Subframe Pitch Contour</c>
+<c><xref target="silk_pitch_contour_pdfs"/></c>
+<c>Voiced frame</c>
+
+<c>Periodicity Index</c>
+<c><xref target="silk_perindex_pdf"/></c>
+<c>Voiced frame</c>
+
+<c>LTP Filter</c>
+<c><xref target="silk_ltp_filter_pdfs"/></c>
+<c>Voiced frame</c>
+
+<c>LTP Scaling</c>
+<c><xref target="silk_ltp_scaling_pdf"/></c>
+<c><xref target="silk_ltp_scaling"/></c>
+
+<c>LCG Seed</c>
+<c><xref target="silk_seed_pdf"/></c>
+<c/>
+
+<c>Excitation Rate Level</c>
+<c><xref target="silk_rate_level_pdfs"/></c>
+<c/>
+
+<c>Excitation Pulse Counts</c>
+<c><xref target="silk_pulse_count_pdfs"/></c>
+<c/>
+
+<c>Excitation Pulse Locations</c>
+<c><xref target="silk_pulse_locations"/></c>
+<c>Non-zero pulse count</c>
+
+<c>Excitation LSBs</c>
+<c><xref target="silk_shell_lsb_pdf"/></c>
+<c><xref target="silk_pulse_counts"/></c>
+
+<c>Excitation Signs</c>
+<c><xref target="silk_sign_pdfs"/></c>
+<c/>
+
+</texttable>
+
+<section anchor="silk_stereo_pred" toc="include"
+ title="Stereo Prediction Weights">
+<t>
+A SILK frame corresponding to the mid channel of a stereo Opus frame begins
+ with a pair of side channel prediction weights, designed such that zeros
+ indicate normal mid-side coupling.
+Since these weights can change on every frame, the first portion of each frame
+ linearly interpolates between the previous weights and the current ones, using
+ zeros for the previous weights if none are available.
+These prediction weights are never included in a mono Opus frame, and the
+ previous weights are reset to zeros on any transition from mono to stereo.
+They are also not included in an LBRR frame for the side channel, even if the
+ LBRR flags indicate the corresponding mid channel was not coded.
+In that case, the previous weights are used, again substituting in zeros if no
+ previous weights are available since the last decoder reset
+ (see <xref target="decoder-reset"/>).
+</t>
+
+<t>
+To summarize, these weights are coded if and only if
+<list style="symbols">
+<t>This is a stereo Opus frame (<xref target="toc_byte"/>), and</t>
+<t>The current SILK frame corresponds to the mid channel.</t>
+</list>
+</t>
+
+<t>
+The prediction weights are coded in three separate pieces, which are decoded
+ by silk_stereo_decode_pred() (decode_stereo_pred.c).
+The first piece jointly codes the high-order part of a table index for both
+ weights.
+The second piece codes the low-order part of each table index.
+The third piece codes an offset used to linearly interpolate between table
+ indices.
+The details are as follows.
+</t>
+
+<t>
+Let n be an index decoded with the 25-element stage-1 PDF in
+ <xref target="silk_stereo_pred_pdfs"/>.
+Then let i0 and i1 be indices decoded with the stage-2 and stage-3 PDFs in
+ <xref target="silk_stereo_pred_pdfs"/>, respectively, and let i2 and i3
+ be two more indices decoded with the stage-2 and stage-3 PDFs, all in that
+ order.
+</t>
+
+<texttable anchor="silk_stereo_pred_pdfs" title="Stereo Weight PDFs">
+<ttcol align="left">Stage</ttcol>
+<ttcol align="left">PDF</ttcol>
+<c>Stage 1</c>
+<c>{7,  2,  1,  1,  1,
+   10, 24,  8,  1,  1,
+    3, 23, 92, 23,  3,
+    1,  1,  8, 24, 10,
+    1,  1,  1,  2,  7}/256</c>
+
+<c>Stage 2</c>
+<c>{85, 86, 85}/256</c>
+
+<c>Stage 3</c>
+<c>{51, 51, 52, 51, 51}/256</c>
+</texttable>
+
+<t>
+Then use n, i0, and i2 to form two table indices, wi0 and wi1, according to
+<figure align="center">
+<artwork align="center"><![CDATA[
+wi0 = i0 + 3*(n/5)
+wi1 = i2 + 3*(n%5)
+]]></artwork>
+</figure>
+ where the division is integer division.
+The range of these indices is 0 to 14, inclusive.
+Let w[i] be the i'th weight from <xref target="silk_stereo_weights_table"/>.
+Then the two prediction weights, w0_Q13 and w1_Q13, are
+<figure align="center">
+<artwork align="center"><![CDATA[
+w1_Q13 = w_Q13[wi1]
+         + ((w_Q13[wi1+1] - w_Q13[wi1])*6554) >> 16)*(2*i3 + 1)
+
+w0_Q13 = w_Q13[wi0]
+         + ((w_Q13[wi0+1] - w_Q13[wi0])*6554) >> 16)*(2*i1 + 1)
+         - w1_Q13
+]]></artwork>
+</figure>
+N.b., w1_Q13 is computed first here, because w0_Q13 depends on it.
+The constant 6554 is approximately 0.1 in Q16.
+Although wi0 and wi1 only have 15 possible values,
+ <xref target="silk_stereo_weights_table"/> contains 16 entries to allow
+ interpolation between entry wi0 and (wi0&nbsp;+&nbsp;1) (and likewise for wi1).
+</t>
+
+<texttable anchor="silk_stereo_weights_table"
+ title="Stereo Weight Table">
+<ttcol align="left">Index</ttcol>
+<ttcol align="right">Weight (Q13)</ttcol>
+ <c>0</c> <c>-13732</c>
+ <c>1</c> <c>-10050</c>
+ <c>2</c>  <c>-8266</c>
+ <c>3</c>  <c>-7526</c>
+ <c>4</c>  <c>-6500</c>
+ <c>5</c>  <c>-5000</c>
+ <c>6</c>  <c>-2950</c>
+ <c>7</c>   <c>-820</c>
+ <c>8</c>    <c>820</c>
+ <c>9</c>   <c>2950</c>
+<c>10</c>   <c>5000</c>
+<c>11</c>   <c>6500</c>
+<c>12</c>   <c>7526</c>
+<c>13</c>   <c>8266</c>
+<c>14</c>  <c>10050</c>
+<c>15</c>  <c>13732</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_mid_only_flag" toc="include" title="Mid-only Flag">
+<t>
+A flag appears after the stereo prediction weights that indicates if only the
+ mid channel is coded for this time interval.
+It appears only when
+<list style="symbols">
+<t>This is a stereo Opus frame (see <xref target="toc_byte"/>),</t>
+<t>The current SILK frame corresponds to the mid channel, and</t>
+<t>Either
+<list style="symbols">
+<t>This is a regular SILK frame where the VAD flags
+ (see <xref target="silk_header_bits"/>) indicate that the corresponding side
+ channel is not active.</t>
+<t>
+This is an LBRR frame where the LBRR flags
+ (see <xref target="silk_header_bits"/> and <xref target="silk_lbrr_flags"/>)
+ indicate that the corresponding side channel is not coded.
+</t>
+</list>
+</t>
+</list>
+It is omitted when there are no stereo weights, for all of the same reasons.
+It is also omitted for a regular SILK frame when the VAD flag of the
+ corresponding side channel frame is set (indicating it is active).
+The side channel must be coded in this case, making the mid-only flag
+ redundant.
+It is also omitted for an LBRR frame when the corresponding LBRR flags
+ indicate the side channel is coded.
+</t>
+
+<t>
+When the flag is present, the decoder reads a single value using the PDF in
+ <xref target="silk_mid_only_pdf"/>, as implemented in
+ silk_stereo_decode_mid_only() (decode_stereo_pred.c).
+If the flag is set, then there is no corresponding SILK frame for the side
+ channel, the entire decoding process for the side channel is skipped, and
+ zeros are fed to the stereo unmixing process (see
+ <xref target="silk_stereo_unmixing"/>) instead.
+As stated above, LBRR frames still include this flag when the LBRR flag
+ indicates that the side channel is not coded.
+In that case, if this flag is zero (indicating that there should be a side
+ channel), then Packet Loss Concealment (PLC, see
+ <xref target="Packet Loss Concealment"/>) SHOULD be invoked to recover a
+ side channel signal.
+Otherwise, the stereo image will collapse.
+</t>
+
+<texttable anchor="silk_mid_only_pdf" title="Mid-only Flag PDF">
+<ttcol align="left">PDF</ttcol>
+<c>{192, 64}/256</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_frame_type" toc="include" title="Frame Type">
+<t>
+Each SILK frame contains a single "frame type" symbol that jointly codes the
+ signal type and quantization offset type of the corresponding frame.
+If the current frame is a regular SILK frame whose VAD bit was not set (an
+ "inactive" frame), then the frame type symbol takes on a value of either 0 or
+ 1 and is decoded using the first PDF in <xref target="silk_frame_type_pdfs"/>.
+If the frame is an LBRR frame or a regular SILK frame whose VAD flag was set
+ (an "active" frame), then the value of the symbol may range from 2 to 5,
+ inclusive, and is decoded using the second PDF in
+ <xref target="silk_frame_type_pdfs"/>.
+<xref target="silk_frame_type_table"/> translates between the value of the
+ frame type symbol and the corresponding signal type and quantization offset
+ type.
+</t>
+
+<texttable anchor="silk_frame_type_pdfs" title="Frame Type PDFs">
+<ttcol>VAD Flag</ttcol>
+<ttcol>PDF</ttcol>
+<c>Inactive</c> <c>{26, 230, 0, 0, 0, 0}/256</c>
+<c>Active</c>   <c>{0, 0, 24, 74, 148, 10}/256</c>
+</texttable>
+
+<texttable anchor="silk_frame_type_table"
+ title="Signal Type and Quantization Offset Type from Frame Type">
+<ttcol>Frame Type</ttcol>
+<ttcol>Signal Type</ttcol>
+<ttcol align="right">Quantization Offset Type</ttcol>
+<c>0</c> <c>Inactive</c> <c>Low</c>
+<c>1</c> <c>Inactive</c> <c>High</c>
+<c>2</c> <c>Unvoiced</c> <c>Low</c>
+<c>3</c> <c>Unvoiced</c> <c>High</c>
+<c>4</c> <c>Voiced</c>   <c>Low</c>
+<c>5</c> <c>Voiced</c>   <c>High</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_gains" toc="include" title="Subframe Gains">
+<t>
+A separate quantization gain is coded for each 5&nbsp;ms subframe.
+These gains control the step size between quantization levels of the excitation
+ signal and, therefore, the quality of the reconstruction.
+They are independent of and unrelated to the pitch contours coded for voiced
+ frames.
+The quantization gains are themselves uniformly quantized to 6&nbsp;bits on a
+ log scale, giving them a resolution of approximately 1.369&nbsp;dB and a range
+ of approximately 1.94&nbsp;dB to 88.21&nbsp;dB.
+</t>
+<t>
+The subframe gains are either coded independently, or relative to the gain from
+ the most recent coded subframe in the same channel.
+Independent coding is used if and only if
+<list style="symbols">
+<t>
+This is the first subframe in the current SILK frame, and
+</t>
+<t>Either
+<list style="symbols">
+<t>
+This is the first SILK frame of its type (LBRR or regular) for this channel in
+ the current Opus frame, or
+ </t>
+<t>
+The previous SILK frame of the same type (LBRR or regular) for this channel in
+ the same Opus frame was not coded.
+</t>
+</list>
+</t>
+</list>
+</t>
+
+<t>
+In an independently coded subframe gain, the 3 most significant bits of the
+ quantization gain are decoded using a PDF selected from
+ <xref target="silk_independent_gain_msb_pdfs"/> based on the decoded signal
+ type (see <xref target="silk_frame_type"/>).
+</t>
+
+<texttable anchor="silk_independent_gain_msb_pdfs"
+ title="PDFs for Independent Quantization Gain MSB Coding">
+<ttcol align="left">Signal Type</ttcol>
+<ttcol align="left">PDF</ttcol>
+<c>Inactive</c> <c>{32, 112, 68, 29, 12,  1,  1, 1}/256</c>
+<c>Unvoiced</c>  <c>{2,  17, 45, 60, 62, 47, 19, 4}/256</c>
+<c>Voiced</c>    <c>{1,   3, 26, 71, 94, 50,  9, 2}/256</c>
+</texttable>
+
+<t>
+The 3 least significant bits are decoded using a uniform PDF:
+</t>
+<texttable anchor="silk_independent_gain_lsb_pdf"
+ title="PDF for Independent Quantization Gain LSB Coding">
+<ttcol align="left">PDF</ttcol>
+<c>{32, 32, 32, 32, 32, 32, 32, 32}/256</c>
+</texttable>
+
+<t>
+These 6 bits are combined to form a value, gain_index, between 0 and 63.
+When the gain for the previous subframe is available, then the current gain is
+ limited as follows:
+<figure align="center">
+<artwork align="center"><![CDATA[
+log_gain = max(gain_index, previous_log_gain - 16) .
+]]></artwork>
+</figure>
+This may help some implementations limit the change in precision of their
+ internal LTP history.
+The indices which this clamp applies to cannot simply be removed from the
+ codebook, because previous_log_gain will not be available after packet loss.
+The clamping is skipped after a decoder reset, and in the side channel if the
+ previous frame in the side channel was not coded, since there is no value for
+ previous_log_gain available.
+It MAY also be skipped after packet loss.
+</t>
+
+<t>
+For subframes which do not have an independent gain (including the first
+ subframe of frames not listed as using independent coding above), the
+ quantization gain is coded relative to the gain from the previous subframe (in
+ the same channel).
+The PDF in <xref target="silk_delta_gain_pdf"/> yields a delta_gain_index value
+ between 0 and 40, inclusive.
+</t>
+<texttable anchor="silk_delta_gain_pdf"
+ title="PDF for Delta Quantization Gain Coding">
+<ttcol align="left">PDF</ttcol>
+<c>{6,   5,  11,  31, 132,  21,   8,   4,
+    3,   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}/256</c>
+</texttable>
+<t>
+The following formula translates this index into a quantization gain for the
+ current subframe using the gain from the previous subframe:
+<figure align="center">
+<artwork align="center"><![CDATA[
+log_gain = clamp(0, max(2*delta_gain_index - 16,
+                   previous_log_gain + delta_gain_index - 4), 63) .
+]]></artwork>
+</figure>
+</t>
+<t>
+silk_gains_dequant() (gain_quant.c) dequantizes log_gain for the k'th subframe
+ and converts it into a linear Q16 scale factor via
+<figure align="center">
+<artwork align="center"><![CDATA[
+gain_Q16[k] = silk_log2lin((0x1D1C71*log_gain>>16) + 2090)
+]]></artwork>
+</figure>
+</t>
+<t>
+The function silk_log2lin() (log2lin.c) computes an approximation of
+ 2**(inLog_Q7/128.0), where inLog_Q7 is its Q7 input.
+Let i = inLog_Q7&gt;&gt;7 be the integer part of inLogQ7 and
+ f = inLog_Q7&amp;127 be the fractional part.
+Then
+<figure align="center">
+<artwork align="center"><![CDATA[
+(1<<i) + ((-174*f*(128-f)>>16)+f)*((1<<i)>>7)
+]]></artwork>
+</figure>
+ yields the approximate exponential.
+The final Q16 gain values lies between 81920 and 1686110208, inclusive
+ (representing scale factors of 1.25 to 25728, respectively).
+</t>
+</section>
+
+<section anchor="silk_nlsfs" toc="include" title="Normalized Line Spectral
+ Frequency (LSF) and Linear Predictive Coding (LPC) Coefficients">
+<t>
+A set of normalized Line Spectral Frequency (LSF) coefficients follow the
+ quantization gains in the bitstream, and represent the Linear Predictive
+ Coding (LPC) coefficients for the current SILK frame.
+Once decoded, the normalized LSFs form an increasing list of Q15 values between
+ 0 and 1.
+These represent the interleaved zeros on the upper half of the unit circle
+ (between 0 and pi, hence "normalized") in the standard decomposition
+ <xref target="line-spectral-pairs"/> of the LPC filter into a symmetric part
+ and an anti-symmetric part (P and Q in <xref target="silk_nlsf2lpc"/>).
+Because of non-linear effects in the decoding process, an implementation SHOULD
+ match the fixed-point arithmetic described in this section exactly.
+An encoder SHOULD also use the same process.
+</t>
+<t>
+The normalized LSFs are coded using a two-stage vector quantizer (VQ)
+ (<xref target="silk_nlsf_stage1"/> and <xref target="silk_nlsf_stage2"/>).
+NB and MB frames use an order-10 predictor, while WB frames use an order-16
+ predictor, and thus have different sets of tables.
+After reconstructing the normalized LSFs
+ (<xref target="silk_nlsf_reconstruction"/>), the decoder runs them through a
+ stabilization process (<xref target="silk_nlsf_stabilization"/>), interpolates
+ them between frames (<xref target="silk_nlsf_interpolation"/>), converts them
+ back into LPC coefficients (<xref target="silk_nlsf2lpc"/>), and then runs
+ them through further processes to limit the range of the coefficients
+ (<xref target="silk_lpc_range_limit"/>) and the gain of the filter
+ (<xref target="silk_lpc_gain_limit"/>).
+All of this is necessary to ensure the reconstruction process is stable.
+</t>
+
+<section anchor="silk_nlsf_stage1" title="Normalized LSF Stage 1 Decoding">
+<t>
+The first VQ stage uses a 32-element codebook, coded with one of the PDFs in
+ <xref target="silk_nlsf_stage1_pdfs"/>, depending on the audio bandwidth and
+ the signal type of the current SILK frame.
+This yields a single index, I1, for the entire frame, which
+<list style="numbers">
+<t>Indexes an element in a coarse codebook,</t>
+<t>Selects the PDFs for the second stage of the VQ, and</t>
+<t>Selects the prediction weights used to remove intra-frame redundancy from
+ the second stage.</t>
+</list>
+The actual codebook elements are listed in
+ <xref target="silk_nlsf_nbmb_codebook"/> and
+ <xref target="silk_nlsf_wb_codebook"/>, but they are not needed until the last
+ stages of reconstructing the LSF coefficients.
+</t>
+
+<texttable anchor="silk_nlsf_stage1_pdfs"
+ title="PDFs for Normalized LSF Stage-1 Index Decoding">
+<ttcol align="left">Audio Bandwidth</ttcol>
+<ttcol align="left">Signal Type</ttcol>
+<ttcol align="left">PDF</ttcol>
+<c>NB or MB</c> <c>Inactive or unvoiced</c>
+<c>
+{44, 34, 30, 19, 21, 12, 11,  3,
+  3,  2, 16,  2,  2,  1,  5,  2,
+  1,  3,  3,  1,  1,  2,  2,  2,
+  3,  1,  9,  9,  2,  7,  2,  1}/256
+</c>
+<c>NB or MB</c> <c>Voiced</c>
+<c>
+{1, 10,  1,  8,  3,  8,  8, 14,
+13, 14,  1, 14, 12, 13, 11, 11,
+12, 11, 10, 10, 11,  8,  9,  8,
+ 7,  8,  1,  1,  6,  1,  6,  5}/256
+</c>
+<c>WB</c> <c>Inactive or unvoiced</c>
+<c>
+{31, 21,  3, 17,  1,  8, 17,  4,
+  1, 18, 16,  4,  2,  3,  1, 10,
+  1,  3, 16, 11, 16,  2,  2,  3,
+  2, 11,  1,  4,  9,  8,  7,  3}/256
+</c>
+<c>WB</c> <c>Voiced</c>
+<c>
+{1,  4, 16,  5, 18, 11,  5, 14,
+15,  1,  3, 12, 13, 14, 14,  6,
+14, 12,  2,  6,  1, 12, 12, 11,
+10,  3, 10,  5,  1,  1,  1,  3}/256
+</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_nlsf_stage2" title="Normalized LSF Stage 2 Decoding">
+<t>
+A total of 16 PDFs are available for the LSF residual in the second stage: the
+ 8 (a...h) for NB and MB frames given in
+ <xref target="silk_nlsf_stage2_nbmb_pdfs"/>, and the 8 (i...p) for WB frames
+ given in <xref target="silk_nlsf_stage2_wb_pdfs"/>.
+Which PDF is used for which coefficient is driven by the index, I1,
+ decoded in the first stage.
+<xref target="silk_nlsf_nbmb_stage2_cb_sel"/> lists the letter of the
+ corresponding PDF for each normalized LSF coefficient for NB and MB, and
+ <xref target="silk_nlsf_wb_stage2_cb_sel"/> lists the same information for WB.
+</t>
+
+<texttable anchor="silk_nlsf_stage2_nbmb_pdfs"
+ title="PDFs for NB/MB Normalized LSF Stage-2 Index Decoding">
+<ttcol align="left">Codebook</ttcol>
+<ttcol align="left">PDF</ttcol>
+<c>a</c> <c>{1,   1,   1,  15, 224,  11,   1,   1,   1}/256</c>
+<c>b</c> <c>{1,   1,   2,  34, 183,  32,   1,   1,   1}/256</c>
+<c>c</c> <c>{1,   1,   4,  42, 149,  55,   2,   1,   1}/256</c>
+<c>d</c> <c>{1,   1,   8,  52, 123,  61,   8,   1,   1}/256</c>
+<c>e</c> <c>{1,   3,  16,  53, 101,  74,   6,   1,   1}/256</c>
+<c>f</c> <c>{1,   3,  17,  55,  90,  73,  15,   1,   1}/256</c>
+<c>g</c> <c>{1,   7,  24,  53,  74,  67,  26,   3,   1}/256</c>
+<c>h</c> <c>{1,   1,  18,  63,  78,  58,  30,   6,   1}/256</c>
+</texttable>
+
+<texttable anchor="silk_nlsf_stage2_wb_pdfs"
+ title="PDFs for WB Normalized LSF Stage-2 Index Decoding">
+<ttcol align="left">Codebook</ttcol>
+<ttcol align="left">PDF</ttcol>
+<c>i</c> <c>{1,   1,   1,   9, 232,   9,   1,   1,   1}/256</c>
+<c>j</c> <c>{1,   1,   2,  28, 186,  35,   1,   1,   1}/256</c>
+<c>k</c> <c>{1,   1,   3,  42, 152,  53,   2,   1,   1}/256</c>
+<c>l</c> <c>{1,   1,  10,  49, 126,  65,   2,   1,   1}/256</c>
+<c>m</c> <c>{1,   4,  19,  48, 100,  77,   5,   1,   1}/256</c>
+<c>n</c> <c>{1,   1,  14,  54, 100,  72,  12,   1,   1}/256</c>
+<c>o</c> <c>{1,   1,  15,  61,  87,  61,  25,   4,   1}/256</c>
+<c>p</c> <c>{1,   7,  21,  50,  77,  81,  17,   1,   1}/256</c>
+</texttable>
+
+<texttable anchor="silk_nlsf_nbmb_stage2_cb_sel"
+ title="Codebook Selection for NB/MB Normalized LSF Stage-2 Index Decoding">
+<ttcol>I1</ttcol>
+<ttcol>Coefficient</ttcol>
+<c/>
+<c><spanx style="vbare">0&nbsp;1&nbsp;2&nbsp;3&nbsp;4&nbsp;5&nbsp;6&nbsp;7&nbsp;8&nbsp;9</spanx></c>
+<c> 0</c>
+<c><spanx style="vbare">a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a</spanx></c>
+<c> 1</c>
+<c><spanx style="vbare">b&nbsp;d&nbsp;b&nbsp;c&nbsp;c&nbsp;b&nbsp;c&nbsp;b&nbsp;b&nbsp;b</spanx></c>
+<c> 2</c>
+<c><spanx style="vbare">c&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b</spanx></c>
+<c> 3</c>
+<c><spanx style="vbare">b&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;b&nbsp;c&nbsp;b&nbsp;b&nbsp;b</spanx></c>
+<c> 4</c>
+<c><spanx style="vbare">c&nbsp;d&nbsp;d&nbsp;d&nbsp;d&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c</spanx></c>
+<c> 5</c>
+<c><spanx style="vbare">a&nbsp;f&nbsp;d&nbsp;d&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;b&nbsp;b</spanx></c>
+<c> g</c>
+<c><spanx style="vbare">a&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;b</spanx></c>
+<c> 7</c>
+<c><spanx style="vbare">c&nbsp;d&nbsp;g&nbsp;e&nbsp;e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f</spanx></c>
+<c> 8</c>
+<c><spanx style="vbare">c&nbsp;e&nbsp;f&nbsp;f&nbsp;e&nbsp;f&nbsp;e&nbsp;g&nbsp;e&nbsp;e</spanx></c>
+<c> 9</c>
+<c><spanx style="vbare">c&nbsp;e&nbsp;e&nbsp;h&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;e</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">e&nbsp;d&nbsp;d&nbsp;d&nbsp;c&nbsp;d&nbsp;c&nbsp;c&nbsp;c&nbsp;c</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">b&nbsp;f&nbsp;f&nbsp;g&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;f</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">c&nbsp;h&nbsp;e&nbsp;g&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;f</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">c&nbsp;h&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">d&nbsp;d&nbsp;f&nbsp;e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;e&nbsp;e</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">c&nbsp;d&nbsp;d&nbsp;f&nbsp;f&nbsp;e&nbsp;e&nbsp;e&nbsp;e&nbsp;e</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">c&nbsp;e&nbsp;e&nbsp;g&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;f</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">c&nbsp;f&nbsp;e&nbsp;g&nbsp;f&nbsp;f&nbsp;f&nbsp;e&nbsp;f&nbsp;e</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">c&nbsp;h&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;f</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">c&nbsp;f&nbsp;e&nbsp;g&nbsp;h&nbsp;g&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">d&nbsp;g&nbsp;h&nbsp;e&nbsp;g&nbsp;f&nbsp;f&nbsp;g&nbsp;e&nbsp;f</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">c&nbsp;h&nbsp;g&nbsp;e&nbsp;e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">e&nbsp;f&nbsp;f&nbsp;e&nbsp;g&nbsp;g&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">c&nbsp;f&nbsp;f&nbsp;g&nbsp;f&nbsp;g&nbsp;e&nbsp;g&nbsp;e&nbsp;e</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">e&nbsp;f&nbsp;f&nbsp;f&nbsp;d&nbsp;h&nbsp;e&nbsp;f&nbsp;f&nbsp;e</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">c&nbsp;d&nbsp;e&nbsp;f&nbsp;f&nbsp;g&nbsp;e&nbsp;f&nbsp;f&nbsp;e</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">c&nbsp;d&nbsp;c&nbsp;d&nbsp;d&nbsp;e&nbsp;c&nbsp;d&nbsp;d&nbsp;d</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">b&nbsp;b&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;d&nbsp;c&nbsp;c</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">e&nbsp;f&nbsp;f&nbsp;g&nbsp;g&nbsp;g&nbsp;f&nbsp;g&nbsp;e&nbsp;f</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">d&nbsp;f&nbsp;f&nbsp;e&nbsp;e&nbsp;e&nbsp;e&nbsp;d&nbsp;d&nbsp;c</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">c&nbsp;f&nbsp;d&nbsp;h&nbsp;f&nbsp;f&nbsp;e&nbsp;e&nbsp;f&nbsp;e</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;g&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
+</texttable>
+
+<texttable anchor="silk_nlsf_wb_stage2_cb_sel"
+ title="Codebook Selection for WB Normalized LSF Stage-2 Index Decoding">
+<ttcol>I1</ttcol>
+<ttcol>Coefficient</ttcol>
+<c/>
+<c><spanx style="vbare">0&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;7&nbsp;&nbsp;8&nbsp;&nbsp;9&nbsp;10&nbsp;11&nbsp;12&nbsp;13&nbsp;14&nbsp;15</spanx></c>
+<c> 0</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i</spanx></c>
+<c> 1</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;l</spanx></c>
+<c> 2</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;p&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;k&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l</spanx></c>
+<c> 3</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;j</spanx></c>
+<c> 4</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;o&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;o&nbsp;&nbsp;m&nbsp;&nbsp;p&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l</spanx></c>
+<c> 5</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;m</spanx></c>
+<c> 6</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i</spanx></c>
+<c> 7</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;k&nbsp;&nbsp;o&nbsp;&nbsp;l&nbsp;&nbsp;p&nbsp;&nbsp;k&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;l</spanx></c>
+<c> 8</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;o&nbsp;&nbsp;k&nbsp;&nbsp;o&nbsp;&nbsp;o&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;o&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l</spanx></c>
+<c> 9</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;j</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;l</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;l</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">l&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;o&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;m</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;o&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;p&nbsp;&nbsp;n&nbsp;&nbsp;k&nbsp;&nbsp;o&nbsp;&nbsp;n&nbsp;&nbsp;p&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;j&nbsp;&nbsp;i</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">j&nbsp;&nbsp;o&nbsp;&nbsp;n&nbsp;&nbsp;p&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;m</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">j&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;m</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">l&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;m</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;o&nbsp;&nbsp;l&nbsp;&nbsp;p&nbsp;&nbsp;p&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;l</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;o&nbsp;&nbsp;o&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;m</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">j&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;j</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;o&nbsp;&nbsp;o&nbsp;&nbsp;m&nbsp;&nbsp;p&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;o&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;o&nbsp;&nbsp;o&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;k&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;p&nbsp;&nbsp;p&nbsp;&nbsp;m&nbsp;&nbsp;m&nbsp;&nbsp;m</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">l&nbsp;&nbsp;l&nbsp;&nbsp;p&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;l</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;i&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;j</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">i&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;j</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">l&nbsp;&nbsp;n&nbsp;&nbsp;n&nbsp;&nbsp;m&nbsp;&nbsp;p&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;i&nbsp;&nbsp;j&nbsp;&nbsp;i</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">k&nbsp;&nbsp;l&nbsp;&nbsp;n&nbsp;&nbsp;l&nbsp;&nbsp;m&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;l&nbsp;&nbsp;k&nbsp;&nbsp;j&nbsp;&nbsp;k&nbsp;&nbsp;o&nbsp;&nbsp;m&nbsp;&nbsp;i&nbsp;&nbsp;i&nbsp;&nbsp;i</spanx></c>
+</texttable>
+
+<t>
+Decoding the second stage residual proceeds as follows.
+For each coefficient, the decoder reads a symbol using the PDF corresponding to
+ I1 from either <xref target="silk_nlsf_nbmb_stage2_cb_sel"/> or
+ <xref target="silk_nlsf_wb_stage2_cb_sel"/>, and subtracts 4 from the result
+ to give an index in the range -4 to 4, inclusive.
+If the index is either -4 or 4, it reads a second symbol using the PDF in
+ <xref target="silk_nlsf_ext_pdf"/>, and adds the value of this second symbol
+ to the index, using the same sign.
+This gives the index, I2[k], a total range of -10 to 10, inclusive.
+</t>
+
+<texttable anchor="silk_nlsf_ext_pdf"
+ title="PDF for Normalized LSF Index Extension Decoding">
+<ttcol align="left">PDF</ttcol>
+<c>{156, 60, 24,  9,  4,  2,  1}/256</c>
+</texttable>
+
+<t>
+The decoded indices from both stages are translated back into normalized LSF
+ coefficients in silk_NLSF_decode() (NLSF_decode.c).
+The stage-2 indices represent residuals after both the first stage of the VQ
+ and a separate backwards-prediction step.
+The backwards prediction process in the encoder subtracts a prediction from
+ each residual formed by a multiple of the coefficient that follows it.
+The decoder must undo this process.
+<xref target="silk_nlsf_pred_weights"/> contains lists of prediction weights
+ for each coefficient.
+There are two lists for NB and MB, and another two lists for WB, giving two
+ possible prediction weights for each coefficient.
+</t>
+
+<texttable anchor="silk_nlsf_pred_weights"
+ title="Prediction Weights for Normalized LSF Decoding">
+<ttcol align="left">Coefficient</ttcol>
+<ttcol align="right">A</ttcol>
+<ttcol align="right">B</ttcol>
+<ttcol align="right">C</ttcol>
+<ttcol align="right">D</ttcol>
+ <c>0</c> <c>179</c> <c>116</c> <c>175</c>  <c>68</c>
+ <c>1</c> <c>138</c>  <c>67</c> <c>148</c>  <c>62</c>
+ <c>2</c> <c>140</c>  <c>82</c> <c>160</c>  <c>66</c>
+ <c>3</c> <c>148</c>  <c>59</c> <c>176</c>  <c>60</c>
+ <c>4</c> <c>151</c>  <c>92</c> <c>178</c>  <c>72</c>
+ <c>5</c> <c>149</c>  <c>72</c> <c>173</c> <c>117</c>
+ <c>6</c> <c>153</c> <c>100</c> <c>174</c>  <c>85</c>
+ <c>7</c> <c>151</c>  <c>89</c> <c>164</c>  <c>90</c>
+ <c>8</c> <c>163</c>  <c>92</c> <c>177</c> <c>118</c>
+ <c>9</c> <c/>        <c/>      <c>174</c> <c>136</c>
+<c>10</c> <c/>        <c/>      <c>196</c> <c>151</c>
+<c>11</c> <c/>        <c/>      <c>182</c> <c>142</c>
+<c>12</c> <c/>        <c/>      <c>198</c> <c>160</c>
+<c>13</c> <c/>        <c/>      <c>192</c> <c>142</c>
+<c>14</c> <c/>        <c/>      <c>182</c> <c>155</c>
+</texttable>
+
+<t>
+The prediction is undone using the procedure implemented in
+ silk_NLSF_residual_dequant() (NLSF_decode.c), which is as follows.
+Each coefficient selects its prediction weight from one of the two lists based
+ on the stage-1 index, I1.
+<xref target="silk_nlsf_nbmb_weight_sel"/> gives the selections for each
+ coefficient for NB and MB, and <xref target="silk_nlsf_wb_weight_sel"/> gives
+ the selections for WB.
+Let d_LPC be the order of the codebook, i.e., 10 for NB and MB, and 16 for WB,
+ and let pred_Q8[k] be the weight for the k'th coefficient selected by this
+ process for 0&nbsp;&lt;=&nbsp;k&nbsp;&lt;&nbsp;d_LPC-1.
+Then, the stage-2 residual for each coefficient is computed via
+<figure align="center">
+<artwork align="center"><![CDATA[
+res_Q10[k] = (k+1 < d_LPC ? (res_Q10[k+1]*pred_Q8[k])>>8 : 0)
+             + ((((I2[k]<<10) - sign(I2[k])*102)*qstep)>>16) ,
+]]></artwork>
+</figure>
+ where qstep is the Q16 quantization step size, which is 11796 for NB and MB
+ and 9830 for WB (representing step sizes of approximately 0.18 and 0.15,
+ respectively).
+</t>
+
+<texttable anchor="silk_nlsf_nbmb_weight_sel"
+ title="Prediction Weight Selection for NB/MB Normalized LSF Decoding">
+<ttcol>I1</ttcol>
+<ttcol>Coefficient</ttcol>
+<c/>
+<c><spanx style="vbare">0&nbsp;1&nbsp;2&nbsp;3&nbsp;4&nbsp;5&nbsp;6&nbsp;7&nbsp;8</spanx></c>
+<c> 0</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c> 1</c>
+<c><spanx style="vbare">B&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c> 2</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c> 3</c>
+<c><spanx style="vbare">B&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c> 4</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c> 5</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c> 6</c>
+<c><spanx style="vbare">B&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c> 7</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;A</spanx></c>
+<c> 8</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;A&nbsp;B&nbsp;B</spanx></c>
+<c> 9</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;B</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;A</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;A</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;A</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">B&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;B</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;B</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;A</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;B&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;A</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;B</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;B&nbsp;B</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;B</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">A&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;B&nbsp;A</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;A</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">B&nbsp;A&nbsp;A&nbsp;B&nbsp;A&nbsp;A&nbsp;A&nbsp;A&nbsp;A</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">A&nbsp;A&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;A&nbsp;B</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">B&nbsp;A&nbsp;B&nbsp;B&nbsp;A&nbsp;B&nbsp;B&nbsp;B&nbsp;B</spanx></c>
+</texttable>
+
+<texttable anchor="silk_nlsf_wb_weight_sel"
+ title="Prediction Weight Selection for WB Normalized LSF Decoding">
+<ttcol>I1</ttcol>
+<ttcol>Coefficient</ttcol>
+<c/>
+<c><spanx style="vbare">0&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;7&nbsp;&nbsp;8&nbsp;&nbsp;9&nbsp;10&nbsp;11&nbsp;12&nbsp;13&nbsp;14</spanx></c>
+<c> 0</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c> 1</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c> 2</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c> 3</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c> 4</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C</spanx></c>
+<c> 5</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c> 6</c>
+<c><spanx style="vbare">D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C</spanx></c>
+<c> 7</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c> 8</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D</spanx></c>
+<c> 9</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;C</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C&nbsp;&nbsp;C&nbsp;&nbsp;D&nbsp;&nbsp;C</spanx></c>
+</texttable>
+
+</section>
+
+<section anchor="silk_nlsf_reconstruction"
+ title="Reconstructing the Normalized LSF Coefficients">
+<t>
+Once the stage-1 index I1 and the stage-2 residual res_Q10[] have been decoded,
+ the final normalized LSF coefficients can be reconstructed.
+</t>
+<t>
+The spectral distortion introduced by the quantization of each LSF coefficient
+ varies, so the stage-2 residual is weighted accordingly, using the
+ low-complexity Inverse Harmonic Mean Weighting (IHMW) function proposed in
+ <xref target="laroia-icassp"/>.
+The weights are derived directly from the stage-1 codebook vector.
+Let cb1_Q8[k] be the k'th entry of the stage-1 codebook vector from
+ <xref target="silk_nlsf_nbmb_codebook"/> or
+ <xref target="silk_nlsf_wb_codebook"/>.
+Then for 0&nbsp;&lt;=&nbsp;k&nbsp;&lt;&nbsp;d_LPC the following expression
+ computes the square of the weight as a Q18 value:
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+w2_Q18[k] = (1024/(cb1_Q8[k] - cb1_Q8[k-1])
+             + 1024/(cb1_Q8[k+1] - cb1_Q8[k])) << 16 ,
+]]>
+</artwork>
+</figure>
+ where cb1_Q8[-1]&nbsp;=&nbsp;0 and cb1_Q8[d_LPC]&nbsp;=&nbsp;256, and the
+ division is integer division.
+This is reduced to an unsquared, Q9 value using the following square-root
+ approximation:
+<figure align="center">
+<artwork align="center"><![CDATA[
+i = ilog(w2_Q18[k])
+f = (w2_Q18[k]>>(i-8)) & 127
+y = ((i&1) ? 32768 : 46214) >> ((32-i)>>1)
+w_Q9[k] = y + ((213*f*y)>>16)
+]]></artwork>
+</figure>
+The constant 46214 here is approximately the square root of 2 in Q15.
+The cb1_Q8[] vector completely determines these weights, and they may be
+ tabulated and stored as 13-bit unsigned values (with a range of 1819 to 5227,
+ inclusive) to avoid computing them when decoding.
+The reference implementation already requires code to compute these weights on
+ unquantized coefficients in the encoder, in silk_NLSF_VQ_weights_laroia()
+ (NLSF_VQ_weights_laroia.c) and its callers, so it reuses that code in the
+ decoder instead of using a pre-computed table to reduce the amount of ROM
+ required.
+</t>
+
+<texttable anchor="silk_nlsf_nbmb_codebook"
+           title="NB/MB Normalized LSF Stage-1 Codebook Vectors">
+<ttcol>I1</ttcol>
+<ttcol>Codebook (Q8)</ttcol>
+<c/>
+<c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;5&nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;&nbsp;7&nbsp;&nbsp;&nbsp;8&nbsp;&nbsp;&nbsp;9</spanx></c>
+<c>0</c>
+<c><spanx style="vbare">12&nbsp;&nbsp;35&nbsp;&nbsp;60&nbsp;&nbsp;83&nbsp;108&nbsp;132&nbsp;157&nbsp;180&nbsp;206&nbsp;228</spanx></c>
+<c>1</c>
+<c><spanx style="vbare">15&nbsp;&nbsp;32&nbsp;&nbsp;55&nbsp;&nbsp;77&nbsp;101&nbsp;125&nbsp;151&nbsp;175&nbsp;201&nbsp;225</spanx></c>
+<c>2</c>
+<c><spanx style="vbare">19&nbsp;&nbsp;42&nbsp;&nbsp;66&nbsp;&nbsp;89&nbsp;114&nbsp;137&nbsp;162&nbsp;184&nbsp;209&nbsp;230</spanx></c>
+<c>3</c>
+<c><spanx style="vbare">12&nbsp;&nbsp;25&nbsp;&nbsp;50&nbsp;&nbsp;72&nbsp;&nbsp;97&nbsp;120&nbsp;147&nbsp;172&nbsp;200&nbsp;223</spanx></c>
+<c>4</c>
+<c><spanx style="vbare">26&nbsp;&nbsp;44&nbsp;&nbsp;69&nbsp;&nbsp;90&nbsp;114&nbsp;135&nbsp;159&nbsp;180&nbsp;205&nbsp;225</spanx></c>
+<c>5</c>
+<c><spanx style="vbare">13&nbsp;&nbsp;22&nbsp;&nbsp;53&nbsp;&nbsp;80&nbsp;106&nbsp;130&nbsp;156&nbsp;180&nbsp;205&nbsp;228</spanx></c>
+<c>6</c>
+<c><spanx style="vbare">15&nbsp;&nbsp;25&nbsp;&nbsp;44&nbsp;&nbsp;64&nbsp;&nbsp;90&nbsp;115&nbsp;142&nbsp;168&nbsp;196&nbsp;222</spanx></c>
+<c>7</c>
+<c><spanx style="vbare">19&nbsp;&nbsp;24&nbsp;&nbsp;62&nbsp;&nbsp;82&nbsp;100&nbsp;120&nbsp;145&nbsp;168&nbsp;190&nbsp;214</spanx></c>
+<c>8</c>
+<c><spanx style="vbare">22&nbsp;&nbsp;31&nbsp;&nbsp;50&nbsp;&nbsp;79&nbsp;103&nbsp;120&nbsp;151&nbsp;170&nbsp;203&nbsp;227</spanx></c>
+<c>9</c>
+<c><spanx style="vbare">21&nbsp;&nbsp;29&nbsp;&nbsp;45&nbsp;&nbsp;65&nbsp;106&nbsp;124&nbsp;150&nbsp;171&nbsp;196&nbsp;224</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">30&nbsp;&nbsp;49&nbsp;&nbsp;75&nbsp;&nbsp;97&nbsp;121&nbsp;142&nbsp;165&nbsp;186&nbsp;209&nbsp;229</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">19&nbsp;&nbsp;25&nbsp;&nbsp;52&nbsp;&nbsp;70&nbsp;&nbsp;93&nbsp;116&nbsp;143&nbsp;166&nbsp;192&nbsp;219</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">26&nbsp;&nbsp;34&nbsp;&nbsp;62&nbsp;&nbsp;75&nbsp;&nbsp;97&nbsp;118&nbsp;145&nbsp;167&nbsp;194&nbsp;217</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">25&nbsp;&nbsp;33&nbsp;&nbsp;56&nbsp;&nbsp;70&nbsp;&nbsp;91&nbsp;113&nbsp;143&nbsp;165&nbsp;196&nbsp;223</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">21&nbsp;&nbsp;34&nbsp;&nbsp;51&nbsp;&nbsp;72&nbsp;&nbsp;97&nbsp;117&nbsp;145&nbsp;171&nbsp;196&nbsp;222</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">20&nbsp;&nbsp;29&nbsp;&nbsp;50&nbsp;&nbsp;67&nbsp;&nbsp;90&nbsp;117&nbsp;144&nbsp;168&nbsp;197&nbsp;221</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">22&nbsp;&nbsp;31&nbsp;&nbsp;48&nbsp;&nbsp;66&nbsp;&nbsp;95&nbsp;117&nbsp;146&nbsp;168&nbsp;196&nbsp;222</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">24&nbsp;&nbsp;33&nbsp;&nbsp;51&nbsp;&nbsp;77&nbsp;116&nbsp;134&nbsp;158&nbsp;180&nbsp;200&nbsp;224</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">21&nbsp;&nbsp;28&nbsp;&nbsp;70&nbsp;&nbsp;87&nbsp;106&nbsp;124&nbsp;149&nbsp;170&nbsp;194&nbsp;217</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">26&nbsp;&nbsp;33&nbsp;&nbsp;53&nbsp;&nbsp;64&nbsp;&nbsp;83&nbsp;117&nbsp;152&nbsp;173&nbsp;204&nbsp;225</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">27&nbsp;&nbsp;34&nbsp;&nbsp;65&nbsp;&nbsp;95&nbsp;108&nbsp;129&nbsp;155&nbsp;174&nbsp;210&nbsp;225</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">20&nbsp;&nbsp;26&nbsp;&nbsp;72&nbsp;&nbsp;99&nbsp;113&nbsp;131&nbsp;154&nbsp;176&nbsp;200&nbsp;219</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">34&nbsp;&nbsp;43&nbsp;&nbsp;61&nbsp;&nbsp;78&nbsp;&nbsp;93&nbsp;114&nbsp;155&nbsp;177&nbsp;205&nbsp;229</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">23&nbsp;&nbsp;29&nbsp;&nbsp;54&nbsp;&nbsp;97&nbsp;124&nbsp;138&nbsp;163&nbsp;179&nbsp;209&nbsp;229</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">30&nbsp;&nbsp;38&nbsp;&nbsp;56&nbsp;&nbsp;89&nbsp;118&nbsp;129&nbsp;158&nbsp;178&nbsp;200&nbsp;231</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">21&nbsp;&nbsp;29&nbsp;&nbsp;49&nbsp;&nbsp;63&nbsp;&nbsp;85&nbsp;111&nbsp;142&nbsp;163&nbsp;193&nbsp;222</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">27&nbsp;&nbsp;48&nbsp;&nbsp;77&nbsp;103&nbsp;133&nbsp;158&nbsp;179&nbsp;196&nbsp;215&nbsp;232</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">29&nbsp;&nbsp;47&nbsp;&nbsp;74&nbsp;&nbsp;99&nbsp;124&nbsp;151&nbsp;176&nbsp;198&nbsp;220&nbsp;237</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">33&nbsp;&nbsp;42&nbsp;&nbsp;61&nbsp;&nbsp;76&nbsp;&nbsp;93&nbsp;121&nbsp;155&nbsp;174&nbsp;207&nbsp;225</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">29&nbsp;&nbsp;53&nbsp;&nbsp;87&nbsp;112&nbsp;136&nbsp;154&nbsp;170&nbsp;188&nbsp;208&nbsp;227</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">24&nbsp;&nbsp;30&nbsp;&nbsp;52&nbsp;&nbsp;84&nbsp;131&nbsp;150&nbsp;166&nbsp;186&nbsp;203&nbsp;229</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">37&nbsp;&nbsp;48&nbsp;&nbsp;64&nbsp;&nbsp;84&nbsp;104&nbsp;118&nbsp;156&nbsp;177&nbsp;201&nbsp;230</spanx></c>
+</texttable>
+
+<texttable anchor="silk_nlsf_wb_codebook"
+           title="WB Normalized LSF Stage-1 Codebook Vectors">
+<ttcol>I1</ttcol>
+<ttcol>Codebook (Q8)</ttcol>
+<c/>
+<c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;5&nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;&nbsp;7&nbsp;&nbsp;&nbsp;8&nbsp;&nbsp;&nbsp;9&nbsp;&nbsp;10&nbsp;&nbsp;11&nbsp;&nbsp;12&nbsp;&nbsp;13&nbsp;&nbsp;14&nbsp;&nbsp;15</spanx></c>
+<c>0</c>
+<c><spanx style="vbare">&nbsp;7&nbsp;23&nbsp;38&nbsp;54&nbsp;69&nbsp;&nbsp;85&nbsp;100&nbsp;116&nbsp;131&nbsp;147&nbsp;162&nbsp;178&nbsp;193&nbsp;208&nbsp;223&nbsp;239</spanx></c>
+<c>1</c>
+<c><spanx style="vbare">13&nbsp;25&nbsp;41&nbsp;55&nbsp;69&nbsp;&nbsp;83&nbsp;&nbsp;98&nbsp;112&nbsp;127&nbsp;142&nbsp;157&nbsp;171&nbsp;187&nbsp;203&nbsp;220&nbsp;236</spanx></c>
+<c>2</c>
+<c><spanx style="vbare">15&nbsp;21&nbsp;34&nbsp;51&nbsp;61&nbsp;&nbsp;78&nbsp;&nbsp;92&nbsp;106&nbsp;126&nbsp;136&nbsp;152&nbsp;167&nbsp;185&nbsp;205&nbsp;225&nbsp;240</spanx></c>
+<c>3</c>
+<c><spanx style="vbare">10&nbsp;21&nbsp;36&nbsp;50&nbsp;63&nbsp;&nbsp;79&nbsp;&nbsp;95&nbsp;110&nbsp;126&nbsp;141&nbsp;157&nbsp;173&nbsp;189&nbsp;205&nbsp;221&nbsp;237</spanx></c>
+<c>4</c>
+<c><spanx style="vbare">17&nbsp;20&nbsp;37&nbsp;51&nbsp;59&nbsp;&nbsp;78&nbsp;&nbsp;89&nbsp;107&nbsp;123&nbsp;134&nbsp;150&nbsp;164&nbsp;184&nbsp;205&nbsp;224&nbsp;240</spanx></c>
+<c>5</c>
+<c><spanx style="vbare">10&nbsp;15&nbsp;32&nbsp;51&nbsp;67&nbsp;&nbsp;81&nbsp;&nbsp;96&nbsp;112&nbsp;129&nbsp;142&nbsp;158&nbsp;173&nbsp;189&nbsp;204&nbsp;220&nbsp;236</spanx></c>
+<c>6</c>
+<c><spanx style="vbare">&nbsp;8&nbsp;21&nbsp;37&nbsp;51&nbsp;65&nbsp;&nbsp;79&nbsp;&nbsp;98&nbsp;113&nbsp;126&nbsp;138&nbsp;155&nbsp;168&nbsp;179&nbsp;192&nbsp;209&nbsp;218</spanx></c>
+<c>7</c>
+<c><spanx style="vbare">12&nbsp;15&nbsp;34&nbsp;55&nbsp;63&nbsp;&nbsp;78&nbsp;&nbsp;87&nbsp;108&nbsp;118&nbsp;131&nbsp;148&nbsp;167&nbsp;185&nbsp;203&nbsp;219&nbsp;236</spanx></c>
+<c>8</c>
+<c><spanx style="vbare">16&nbsp;19&nbsp;32&nbsp;36&nbsp;56&nbsp;&nbsp;79&nbsp;&nbsp;91&nbsp;108&nbsp;118&nbsp;136&nbsp;154&nbsp;171&nbsp;186&nbsp;204&nbsp;220&nbsp;237</spanx></c>
+<c>9</c>
+<c><spanx style="vbare">11&nbsp;28&nbsp;43&nbsp;58&nbsp;74&nbsp;&nbsp;89&nbsp;105&nbsp;120&nbsp;135&nbsp;150&nbsp;165&nbsp;180&nbsp;196&nbsp;211&nbsp;226&nbsp;241</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">&nbsp;6&nbsp;16&nbsp;33&nbsp;46&nbsp;60&nbsp;&nbsp;75&nbsp;&nbsp;92&nbsp;107&nbsp;123&nbsp;137&nbsp;156&nbsp;169&nbsp;185&nbsp;199&nbsp;214&nbsp;225</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">11&nbsp;19&nbsp;30&nbsp;44&nbsp;57&nbsp;&nbsp;74&nbsp;&nbsp;89&nbsp;105&nbsp;121&nbsp;135&nbsp;152&nbsp;169&nbsp;186&nbsp;202&nbsp;218&nbsp;234</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">12&nbsp;19&nbsp;29&nbsp;46&nbsp;57&nbsp;&nbsp;71&nbsp;&nbsp;88&nbsp;100&nbsp;120&nbsp;132&nbsp;148&nbsp;165&nbsp;182&nbsp;199&nbsp;216&nbsp;233</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">17&nbsp;23&nbsp;35&nbsp;46&nbsp;56&nbsp;&nbsp;77&nbsp;&nbsp;92&nbsp;106&nbsp;123&nbsp;134&nbsp;152&nbsp;167&nbsp;185&nbsp;204&nbsp;222&nbsp;237</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">14&nbsp;17&nbsp;45&nbsp;53&nbsp;63&nbsp;&nbsp;75&nbsp;&nbsp;89&nbsp;107&nbsp;115&nbsp;132&nbsp;151&nbsp;171&nbsp;188&nbsp;206&nbsp;221&nbsp;240</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">&nbsp;9&nbsp;16&nbsp;29&nbsp;40&nbsp;56&nbsp;&nbsp;71&nbsp;&nbsp;88&nbsp;103&nbsp;119&nbsp;137&nbsp;154&nbsp;171&nbsp;189&nbsp;205&nbsp;222&nbsp;237</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">16&nbsp;19&nbsp;36&nbsp;48&nbsp;57&nbsp;&nbsp;76&nbsp;&nbsp;87&nbsp;105&nbsp;118&nbsp;132&nbsp;150&nbsp;167&nbsp;185&nbsp;202&nbsp;218&nbsp;236</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">12&nbsp;17&nbsp;29&nbsp;54&nbsp;71&nbsp;&nbsp;81&nbsp;&nbsp;94&nbsp;104&nbsp;126&nbsp;136&nbsp;149&nbsp;164&nbsp;182&nbsp;201&nbsp;221&nbsp;237</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">15&nbsp;28&nbsp;47&nbsp;62&nbsp;79&nbsp;&nbsp;97&nbsp;115&nbsp;129&nbsp;142&nbsp;155&nbsp;168&nbsp;180&nbsp;194&nbsp;208&nbsp;223&nbsp;238</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">&nbsp;8&nbsp;14&nbsp;30&nbsp;45&nbsp;62&nbsp;&nbsp;78&nbsp;&nbsp;94&nbsp;111&nbsp;127&nbsp;143&nbsp;159&nbsp;175&nbsp;192&nbsp;207&nbsp;223&nbsp;239</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">17&nbsp;30&nbsp;49&nbsp;62&nbsp;79&nbsp;&nbsp;92&nbsp;107&nbsp;119&nbsp;132&nbsp;145&nbsp;160&nbsp;174&nbsp;190&nbsp;204&nbsp;220&nbsp;235</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">14&nbsp;19&nbsp;36&nbsp;45&nbsp;61&nbsp;&nbsp;76&nbsp;&nbsp;91&nbsp;108&nbsp;121&nbsp;138&nbsp;154&nbsp;172&nbsp;189&nbsp;205&nbsp;222&nbsp;238</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">12&nbsp;18&nbsp;31&nbsp;45&nbsp;60&nbsp;&nbsp;76&nbsp;&nbsp;91&nbsp;107&nbsp;123&nbsp;138&nbsp;154&nbsp;171&nbsp;187&nbsp;204&nbsp;221&nbsp;236</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">13&nbsp;17&nbsp;31&nbsp;43&nbsp;53&nbsp;&nbsp;70&nbsp;&nbsp;83&nbsp;103&nbsp;114&nbsp;131&nbsp;149&nbsp;167&nbsp;185&nbsp;203&nbsp;220&nbsp;237</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">17&nbsp;22&nbsp;35&nbsp;42&nbsp;58&nbsp;&nbsp;78&nbsp;&nbsp;93&nbsp;110&nbsp;125&nbsp;139&nbsp;155&nbsp;170&nbsp;188&nbsp;206&nbsp;224&nbsp;240</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">&nbsp;8&nbsp;15&nbsp;34&nbsp;50&nbsp;67&nbsp;&nbsp;83&nbsp;&nbsp;99&nbsp;115&nbsp;131&nbsp;146&nbsp;162&nbsp;178&nbsp;193&nbsp;209&nbsp;224&nbsp;239</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">13&nbsp;16&nbsp;41&nbsp;66&nbsp;73&nbsp;&nbsp;86&nbsp;&nbsp;95&nbsp;111&nbsp;128&nbsp;137&nbsp;150&nbsp;163&nbsp;183&nbsp;206&nbsp;225&nbsp;241</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">17&nbsp;25&nbsp;37&nbsp;52&nbsp;63&nbsp;&nbsp;75&nbsp;&nbsp;92&nbsp;102&nbsp;119&nbsp;132&nbsp;144&nbsp;160&nbsp;175&nbsp;191&nbsp;212&nbsp;231</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">19&nbsp;31&nbsp;49&nbsp;65&nbsp;83&nbsp;100&nbsp;117&nbsp;133&nbsp;147&nbsp;161&nbsp;174&nbsp;187&nbsp;200&nbsp;213&nbsp;227&nbsp;242</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">18&nbsp;31&nbsp;52&nbsp;68&nbsp;88&nbsp;103&nbsp;117&nbsp;126&nbsp;138&nbsp;149&nbsp;163&nbsp;177&nbsp;192&nbsp;207&nbsp;223&nbsp;239</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">16&nbsp;29&nbsp;47&nbsp;61&nbsp;76&nbsp;&nbsp;90&nbsp;106&nbsp;119&nbsp;133&nbsp;147&nbsp;161&nbsp;176&nbsp;193&nbsp;209&nbsp;224&nbsp;240</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">15&nbsp;21&nbsp;35&nbsp;50&nbsp;61&nbsp;&nbsp;73&nbsp;&nbsp;86&nbsp;&nbsp;97&nbsp;110&nbsp;119&nbsp;129&nbsp;141&nbsp;175&nbsp;198&nbsp;218&nbsp;237</spanx></c>
+</texttable>
+
+<t>
+Given the stage-1 codebook entry cb1_Q8[], the stage-2 residual res_Q10[], and
+ their corresponding weights, w_Q9[], the reconstructed normalized LSF
+ coefficients are
+<figure align="center">
+<artwork align="center"><![CDATA[
+NLSF_Q15[k] = clamp(0,
+               (cb1_Q8[k]<<7) + (res_Q10[k]<<14)/w_Q9[k], 32767) ,
+]]></artwork>
+</figure>
+ where the division is integer division.
+However, nothing in either the reconstruction process or the
+ quantization process in the encoder thus far guarantees that the coefficients
+ are monotonically increasing and separated well enough to ensure a stable
+ filter <xref target="Kabal86"/>.
+When using the reference encoder, roughly 2% of frames violate this constraint.
+The next section describes a stabilization procedure used to make these
+ guarantees.
+</t>
+
+</section>
+
+<section anchor="silk_nlsf_stabilization" title="Normalized LSF Stabilization">
+<t>
+The normalized LSF stabilization procedure is implemented in
+ silk_NLSF_stabilize() (NLSF_stabilize.c).
+This process ensures that consecutive values of the normalized LSF
+ coefficients, NLSF_Q15[], are spaced some minimum distance apart
+ (predetermined to be the 0.01 percentile of a large training set).
+<xref target="silk_nlsf_min_spacing"/> gives the minimum spacings for NB and MB
+ and those for WB, where row k is the minimum allowed value of
+ NLSF_Q[k]-NLSF_Q[k-1].
+For the purposes of computing this spacing for the first and last coefficient,
+ NLSF_Q15[-1] is taken to be 0, and NLSF_Q15[d_LPC] is taken to be 32768.
+</t>
+
+<texttable anchor="silk_nlsf_min_spacing"
+           title="Minimum Spacing for Normalized LSF Coefficients">
+<ttcol>Coefficient</ttcol>
+<ttcol align="right">NB and MB</ttcol>
+<ttcol align="right">WB</ttcol>
+ <c>0</c> <c>250</c> <c>100</c>
+ <c>1</c>   <c>3</c>   <c>3</c>
+ <c>2</c>   <c>6</c>  <c>40</c>
+ <c>3</c>   <c>3</c>   <c>3</c>
+ <c>4</c>   <c>3</c>   <c>3</c>
+ <c>5</c>   <c>3</c>   <c>3</c>
+ <c>6</c>   <c>4</c>   <c>5</c>
+ <c>7</c>   <c>3</c>  <c>14</c>
+ <c>8</c>   <c>3</c>  <c>14</c>
+ <c>9</c>   <c>3</c>  <c>10</c>
+<c>10</c> <c>461</c>  <c>11</c>
+<c>11</c>       <c/>   <c>3</c>
+<c>12</c>       <c/>   <c>8</c>
+<c>13</c>       <c/>   <c>9</c>
+<c>14</c>       <c/>   <c>7</c>
+<c>15</c>       <c/>   <c>3</c>
+<c>16</c>       <c/> <c>347</c>
+</texttable>
+
+<t>
+The procedure starts off by trying to make small adjustments which attempt to
+ minimize the amount of distortion introduced.
+After 20 such adjustments, it falls back to a more direct method which
+ guarantees the constraints are enforced but may require large adjustments.
+</t>
+<t>
+Let NDeltaMin_Q15[k] be the minimum required spacing for the current audio
+ bandwidth from <xref target="silk_nlsf_min_spacing"/>.
+First, the procedure finds the index i where
+ NLSF_Q15[i]&nbsp;-&nbsp;NLSF_Q15[i-1]&nbsp;-&nbsp;NDeltaMin_Q15[i] is the
+ smallest, breaking ties by using the lower value of i.
+If this value is non-negative, then the stabilization stops; the coefficients
+ satisfy all the constraints.
+Otherwise, if i&nbsp;==&nbsp;0, it sets NLSF_Q15[0] to NDeltaMin_Q15[0], and if
+ i&nbsp;==&nbsp;d_LPC, it sets NLSF_Q15[d_LPC-1] to
+ (32768&nbsp;-&nbsp;NDeltaMin_Q15[d_LPC]).
+For all other values of i, both NLSF_Q15[i-1] and NLSF_Q15[i] are updated as
+ follows:
+<figure align="center">
+<artwork align="center"><![CDATA[
+                                          i-1
+                                          __
+ min_center_Q15 = (NDeltaMin_Q15[i]>>1) + \  NDeltaMin_Q15[k]
+                                          /_
+                                          k=0
+                                                 d_LPC
+                                                  __
+ max_center_Q15 = 32768 - (NDeltaMin_Q15[i]>>1) - \  NDeltaMin_Q15[k]
+                                                  /_
+                                                 k=i+1
+center_freq_Q15 = clamp(min_center_Q15[i],
+                        (NLSF_Q15[i-1] + NLSF_Q15[i] + 1)>>1,
+                        max_center_Q15[i])
+
+ NLSF_Q15[i-1] = center_freq_Q15 - (NDeltaMin_Q15[i]>>1)
+
+   NLSF_Q15[i] = NLSF_Q15[i-1] + NDeltaMin_Q15[i] .
+]]></artwork>
+</figure>
+Then the procedure repeats again, until it has either executed 20 times or
+ has stopped because the coefficients satisfy all the constraints.
+</t>
+<t>
+After the 20th repetition of the above procedure, the following fallback
+ procedure executes once.
+First, the values of NLSF_Q15[k] for 0&nbsp;&lt;=&nbsp;k&nbsp;&lt;&nbsp;d_LPC
+ are sorted in ascending order.
+Then for each value of k from 0 to d_LPC-1, NLSF_Q15[k] is set to
+<figure align="center">
+<artwork align="center"><![CDATA[
+max(NLSF_Q15[k], NLSF_Q15[k-1] + NDeltaMin_Q15[k]) .
+]]></artwork>
+</figure>
+Next, for each value of k from d_LPC-1 down to 0, NLSF_Q15[k] is set to
+<figure align="center">
+<artwork align="center"><![CDATA[
+min(NLSF_Q15[k], NLSF_Q15[k+1] - NDeltaMin_Q15[k+1]) .
+]]></artwork>
+</figure>
+</t>
+
+</section>
+
+<section anchor="silk_nlsf_interpolation" title="Normalized LSF Interpolation">
+<t>
+For 20&nbsp;ms SILK frames, the first half of the frame (i.e., the first two
+ subframes) may use normalized LSF coefficients that are interpolated between
+ the decoded LSFs for the most recent coded frame (in the same channel) and the
+ current frame.
+A Q2 interpolation factor follows the LSF coefficient indices in the bitstream,
+ which is decoded using the PDF in <xref target="silk_nlsf_interp_pdf"/>.
+This happens in silk_decode_indices() (decode_indices.c).
+After either
+<list style="symbols">
+<t>An uncoded regular SILK frame in the side channel, or</t>
+<t>A decoder reset (see <xref target="decoder-reset"/>),</t>
+</list>
+ the decoder still decodes this factor, but ignores its value and always uses
+ 4 instead.
+For 10&nbsp;ms SILK frames, this factor is not stored at all.
+</t>
+
+<texttable anchor="silk_nlsf_interp_pdf"
+           title="PDF for Normalized LSF Interpolation Index">
+<ttcol>PDF</ttcol>
+<c>{13, 22, 29, 11, 181}/256</c>
+</texttable>
+
+<t>
+Let n2_Q15[k] be the normalized LSF coefficients decoded by the procedure in
+ <xref target="silk_nlsfs"/>, n0_Q15[k] be the LSF coefficients
+ decoded for the prior frame, and w_Q2 be the interpolation factor.
+Then the normalized LSF coefficients used for the first half of a 20&nbsp;ms
+ frame, n1_Q15[k], are
+<figure align="center">
+<artwork align="center"><![CDATA[
+n1_Q15[k] = n0_Q15[k] + (w_Q2*(n2_Q15[k] - n0_Q15[k]) >> 2) .
+]]></artwork>
+</figure>
+This interpolation is performed in silk_decode_parameters()
+ (decode_parameters.c).
+</t>
+</section>
+
+<section anchor="silk_nlsf2lpc"
+ title="Converting Normalized LSFs to LPC Coefficients">
+<t>
+Any LPC filter A(z) can be split into a symmetric part P(z) and an
+ anti-symmetric part Q(z) such that
+<figure align="center">
+<artwork align="center"><![CDATA[
+          d_LPC
+           __         -k   1
+A(z) = 1 - \  a[k] * z   = - * (P(z) + Q(z))
+           /_              2
+           k=1
+]]></artwork>
+</figure>
+with
+<figure align="center">
+<artwork align="center"><![CDATA[
+               -d_LPC-1      -1
+P(z) = A(z) + z         * A(z  )
+
+               -d_LPC-1      -1
+Q(z) = A(z) - z         * A(z  ) .
+]]></artwork>
+</figure>
+The even normalized LSF coefficients correspond to a pair of conjugate roots of
+ P(z), while the odd coefficients correspond to a pair of conjugate roots of
+ Q(z), all of which lie on the unit circle.
+In addition, P(z) has a root at pi and Q(z) has a root at 0.
+Thus, they may be reconstructed mathematically from a set of normalized LSF
+ coefficients, n[k], as
+<figure align="center">
+<artwork align="center"><![CDATA[
+                 d_LPC/2-1
+             -1     ___                        -1    -2
+P(z) = (1 + z  ) *  | |  (1 - 2*cos(pi*n[2*k])*z  + z  )
+                    k=0
+
+                 d_LPC/2-1
+             -1     ___                          -1    -2
+Q(z) = (1 - z  ) *  | |  (1 - 2*cos(pi*n[2*k+1])*z  + z  )
+                    k=0
+]]></artwork>
+</figure>
+</t>
+<t>
+However, SILK performs this reconstruction using a fixed-point approximation so
+ that all decoders can reproduce it in a bit-exact manner to avoid prediction
+ drift.
+The function silk_NLSF2A() (NLSF2A.c) implements this procedure.
+</t>
+<t>
+To start, it approximates cos(pi*n[k]) using a table lookup with linear
+ interpolation.
+The encoder SHOULD use the inverse of this piecewise linear approximation,
+ rather than the true inverse of the cosine function, when deriving the
+ normalized LSF coefficients.
+These values are also re-ordered to improve numerical accuracy when
+ constructing the LPC polynomials.
+</t>
+
+<texttable anchor="silk_nlsf_orderings"
+           title="LSF Ordering for Polynomial Evaluation">
+<ttcol>Coefficient</ttcol>
+<ttcol align="right">NB and MB</ttcol>
+<ttcol align="right">WB</ttcol>
+ <c>0</c>  <c>0</c>  <c>0</c>
+ <c>1</c>  <c>9</c> <c>15</c>
+ <c>2</c>  <c>6</c>  <c>8</c>
+ <c>3</c>  <c>3</c>  <c>7</c>
+ <c>4</c>  <c>4</c>  <c>4</c>
+ <c>5</c>  <c>5</c> <c>11</c>
+ <c>6</c>  <c>8</c> <c>12</c>
+ <c>7</c>  <c>1</c>  <c>3</c>
+ <c>8</c>  <c>2</c>  <c>2</c>
+ <c>9</c>  <c>7</c> <c>13</c>
+<c>10</c>      <c/> <c>10</c>
+<c>11</c>      <c/>  <c>5</c>
+<c>12</c>      <c/>  <c>6</c>
+<c>13</c>      <c/>  <c>9</c>
+<c>14</c>      <c/> <c>14</c>
+<c>15</c>      <c/>  <c>1</c>
+</texttable>
+
+<t>
+The top 7 bits of each normalized LSF coefficient index a value in the table,
+ and the next 8 bits interpolate between it and the next value.
+Let i&nbsp;=&nbsp;(n[k]&nbsp;&gt;&gt;&nbsp;8) be the integer index and
+ f&nbsp;=&nbsp;(n[k]&nbsp;&amp;&nbsp;255) be the fractional part of a given
+ coefficient.
+Then the re-ordered, approximated cosine, c_Q17[ordering[k]], is
+<figure align="center">
+<artwork align="center"><![CDATA[
+c_Q17[ordering[k]] = (cos_Q12[i]*256
+                      + (cos_Q12[i+1]-cos_Q12[i])*f + 4) >> 3 ,
+]]></artwork>
+</figure>
+ where ordering[k] is the k'th entry of the column of
+ <xref target="silk_nlsf_orderings"/> corresponding to the current audio
+ bandwidth and cos_Q12[i] is the i'th entry of <xref target="silk_cos_table"/>.
+</t>
+
+<texttable anchor="silk_cos_table"
+           title="Q12 Cosine Table for LSF Conversion">
+<ttcol align="right">i</ttcol>
+<ttcol align="right">+0</ttcol>
+<ttcol align="right">+1</ttcol>
+<ttcol align="right">+2</ttcol>
+<ttcol align="right">+3</ttcol>
+<c>0</c>
+ <c>4096</c> <c>4095</c> <c>4091</c> <c>4085</c>
+<c>4</c>
+ <c>4076</c> <c>4065</c> <c>4052</c> <c>4036</c>
+<c>8</c>
+ <c>4017</c> <c>3997</c> <c>3973</c> <c>3948</c>
+<c>12</c>
+ <c>3920</c> <c>3889</c> <c>3857</c> <c>3822</c>
+<c>16</c>
+ <c>3784</c> <c>3745</c> <c>3703</c> <c>3659</c>
+<c>20</c>
+ <c>3613</c> <c>3564</c> <c>3513</c> <c>3461</c>
+<c>24</c>
+ <c>3406</c> <c>3349</c> <c>3290</c> <c>3229</c>
+<c>28</c>
+ <c>3166</c> <c>3102</c> <c>3035</c> <c>2967</c>
+<c>32</c>
+ <c>2896</c> <c>2824</c> <c>2751</c> <c>2676</c>
+<c>36</c>
+ <c>2599</c> <c>2520</c> <c>2440</c> <c>2359</c>
+<c>40</c>
+ <c>2276</c> <c>2191</c> <c>2106</c> <c>2019</c>
+<c>44</c>
+ <c>1931</c> <c>1842</c> <c>1751</c> <c>1660</c>
+<c>48</c>
+ <c>1568</c> <c>1474</c> <c>1380</c> <c>1285</c>
+<c>52</c>
+ <c>1189</c> <c>1093</c>  <c>995</c>  <c>897</c>
+<c>56</c>
+  <c>799</c>  <c>700</c>  <c>601</c>  <c>501</c>
+<c>60</c>
+  <c>401</c>  <c>301</c>  <c>201</c>  <c>101</c>
+<c>64</c>
+    <c>0</c> <c>-101</c> <c>-201</c> <c>-301</c>
+<c>68</c>
+ <c>-401</c> <c>-501</c> <c>-601</c> <c>-700</c>
+<c>72</c>
+ <c>-799</c> <c>-897</c> <c>-995</c> <c>-1093</c>
+<c>76</c>
+<c>-1189</c><c>-1285</c><c>-1380</c><c>-1474</c>
+<c>80</c>
+<c>-1568</c><c>-1660</c><c>-1751</c><c>-1842</c>
+<c>84</c>
+<c>-1931</c><c>-2019</c><c>-2106</c><c>-2191</c>
+<c>88</c>
+<c>-2276</c><c>-2359</c><c>-2440</c><c>-2520</c>
+<c>92</c>
+<c>-2599</c><c>-2676</c><c>-2751</c><c>-2824</c>
+<c>96</c>
+<c>-2896</c><c>-2967</c><c>-3035</c><c>-3102</c>
+<c>100</c>
+<c>-3166</c><c>-3229</c><c>-3290</c><c>-3349</c>
+<c>104</c>
+<c>-3406</c><c>-3461</c><c>-3513</c><c>-3564</c>
+<c>108</c>
+<c>-3613</c><c>-3659</c><c>-3703</c><c>-3745</c>
+<c>112</c>
+<c>-3784</c><c>-3822</c><c>-3857</c><c>-3889</c>
+<c>116</c>
+<c>-3920</c><c>-3948</c><c>-3973</c><c>-3997</c>
+<c>120</c>
+<c>-4017</c><c>-4036</c><c>-4052</c><c>-4065</c>
+<c>124</c>
+<c>-4076</c><c>-4085</c><c>-4091</c><c>-4095</c>
+<c>128</c>
+<c>-4096</c>        <c/>        <c/>        <c/>
+</texttable>
+
+<t>
+Given the list of cosine values, silk_NLSF2A_find_poly() (NLSF2A.c)
+ computes the coefficients of P and Q, described here via a simple recurrence.
+Let p_Q16[k][j] and q_Q16[k][j] be the coefficients of the products of the
+ first (k+1) root pairs for P and Q, with j indexing the coefficient number.
+Only the first (k+2) coefficients are needed, as the products are symmetric.
+Let p_Q16[0][0]&nbsp;=&nbsp;q_Q16[0][0]&nbsp;=&nbsp;1&lt;&lt;16,
+ p_Q16[0][1]&nbsp;=&nbsp;-c_Q17[0], q_Q16[0][1]&nbsp;=&nbsp;-c_Q17[1], and
+ d2&nbsp;=&nbsp;d_LPC/2.
+As boundary conditions, assume
+ p_Q16[k][j]&nbsp;=&nbsp;q_Q16[k][j]&nbsp;=&nbsp;0 for all
+ j&nbsp;&lt;&nbsp;0.
+Also, assume p_Q16[k][k+2]&nbsp;=&nbsp;p_Q16[k][k] and
+ q_Q16[k][k+2]&nbsp;=&nbsp;q_Q16[k][k] (because of the symmetry).
+Then, for 0&nbsp;&lt;&nbsp;k&nbsp;&lt;&nbsp;d2 and 0&nbsp;&lt;=&nbsp;j&nbsp;&lt;=&nbsp;k+1,
+<figure align="center">
+<artwork align="center"><![CDATA[
+p_Q16[k][j] = p_Q16[k-1][j] + p_Q16[k-1][j-2]
+              - ((c_Q17[2*k]*p_Q16[k-1][j-1] + 32768)>>16) ,
+
+q_Q16[k][j] = q_Q16[k-1][j] + q_Q16[k-1][j-2]
+              - ((c_Q17[2*k+1]*q_Q16[k-1][j-1] + 32768)>>16) .
+]]></artwork>
+</figure>
+The use of Q17 values for the cosine terms in an otherwise Q16 expression
+ implicitly scales them by a factor of 2.
+The multiplications in this recurrence may require up to 48 bits of precision
+ in the result to avoid overflow.
+In practice, each row of the recurrence only depends on the previous row, so an
+ implementation does not need to store all of them.
+</t>
+<t>
+silk_NLSF2A() uses the values from the last row of this recurrence to
+ reconstruct a 32-bit version of the LPC filter (without the leading 1.0
+ coefficient), a32_Q17[k], 0&nbsp;&lt;=&nbsp;k&nbsp;&lt;&nbsp;d2:
+<figure align="center">
+<artwork align="center"><![CDATA[
+a32_Q17[k]         = -(q_Q16[d2-1][k+1] - q_Q16[d2-1][k])
+                     - (p_Q16[d2-1][k+1] + p_Q16[d2-1][k])) ,
+
+a32_Q17[d_LPC-k-1] =  (q_Q16[d2-1][k+1] - q_Q16[d2-1][k])
+                     - (p_Q16[d2-1][k+1] + p_Q16[d2-1][k])) .
+]]></artwork>
+</figure>
+The sum and difference of two terms from each of the p_Q16 and q_Q16
+ coefficient lists reflect the (1&nbsp;+&nbsp;z**-1) and
+ (1&nbsp;-&nbsp;z**-1) factors of P and Q, respectively.
+The promotion of the expression from Q16 to Q17 implicitly scales the result
+ by 1/2.
+</t>
+</section>
+
+<section anchor="silk_lpc_range_limit"
+ title="Limiting the Range of the LPC Coefficients">
+<t>
+The a32_Q17[] coefficients are too large to fit in a 16-bit value, which
+ significantly increases the cost of applying this filter in fixed-point
+ decoders.
+Reducing them to Q12 precision doesn't incur any significant quality loss,
+ but still does not guarantee they will fit.
+silk_NLSF2A() applies up to 10 rounds of bandwidth expansion to limit
+ the dynamic range of these coefficients.
+Even floating-point decoders SHOULD perform these steps, to avoid mismatch.
+</t>
+<t>
+For each round, the process first finds the index k such that abs(a32_Q17[k])
+ is largest, breaking ties by choosing the lowest value of k.
+Then, it computes the corresponding Q12 precision value, maxabs_Q12, subject to
+ an upper bound to avoid overflow in subsequent computations:
+<figure align="center">
+<artwork align="center"><![CDATA[
+maxabs_Q12 = min((maxabs_Q17 + 16) >> 5, 163838) .
+]]></artwork>
+</figure>
+If this is larger than 32767, the procedure derives the chirp factor,
+ sc_Q16[0], to use in the bandwidth expansion as
+<figure align="center">
+<artwork align="center"><![CDATA[
+                    (maxabs_Q12 - 32767) << 14
+sc_Q16[0] = 65470 - -------------------------- ,
+                    (maxabs_Q12 * (k+1)) >> 2
+]]></artwork>
+</figure>
+ where the division here is integer division.
+This is an approximation of the chirp factor needed to reduce the target
+ coefficient to 32767, though it is both less than 0.999 and, for
+ k&nbsp;&gt;&nbsp;0 when maxabs_Q12 is much greater than 32767, still slightly
+ too large.
+The upper bound on maxabs_Q12, 163838, was chosen because it is equal to
+ ((2**31&nbsp;-&nbsp;1)&nbsp;&gt;&gt;&nbsp;14)&nbsp;+&nbsp;32767, i.e., the
+ largest value of maxabs_Q12 that would not overflow the numerator in the
+ equation above when stored in a signed 32-bit integer.
+</t>
+<t>
+silk_bwexpander_32() (bwexpander_32.c) performs the bandwidth expansion (again,
+ only when maxabs_Q12 is greater than 32767) using the following recurrence:
+<figure align="center">
+<artwork align="center"><![CDATA[
+ a32_Q17[k] = (a32_Q17[k]*sc_Q16[k]) >> 16
+
+sc_Q16[k+1] = (sc_Q16[0]*sc_Q16[k] + 32768) >> 16
+]]></artwork>
+</figure>
+The first multiply may require up to 48 bits of precision in the result to
+ avoid overflow.
+The second multiply must be unsigned to avoid overflow with only 32 bits of
+ precision.
+The reference implementation uses a slightly more complex formulation that
+ avoids the 32-bit overflow using signed multiplication, but is otherwise
+ equivalent.
+</t>
+<t>
+After 10 rounds of bandwidth expansion are performed, they are simply saturated
+ to 16 bits:
+<figure align="center">
+<artwork align="center"><![CDATA[
+a32_Q17[k] = clamp(-32768, (a32_Q17[k] + 16) >> 5, 32767) << 5 .
+]]></artwork>
+</figure>
+Because this performs the actual saturation in the Q12 domain, but converts the
+ coefficients back to the Q17 domain for the purposes of prediction gain
+ limiting, this step must be performed after the 10th round of bandwidth
+ expansion, regardless of whether or not the Q12 version of any coefficient
+ still overflows a 16-bit integer.
+This saturation is not performed if maxabs_Q12 drops to 32767 or less prior to
+ the 10th round.
+</t>
+</section>
+
+<section anchor="silk_lpc_gain_limit"
+ title="Limiting the Prediction Gain of the LPC Filter">
+<t>
+The prediction gain of an LPC synthesis filter is the square-root of the output
+ energy when the filter is excited by a unit-energy impulse.
+Even if the Q12 coefficients would fit, the resulting filter may still have a
+ significant gain (especially for voiced sounds), making the filter unstable.
+silk_NLSF2A() applies up to 18 additional rounds of bandwidth expansion to
+ limit the prediction gain.
+Instead of controlling the amount of bandwidth expansion using the prediction
+ gain itself (which may diverge to infinity for an unstable filter),
+ silk_NLSF2A() uses silk_LPC_inverse_pred_gain_QA() (LPC_inv_pred_gain.c) to
+ compute the reflection coefficients associated with the filter.
+The filter is stable if and only if the magnitude of these coefficients is
+ sufficiently less than one.
+The reflection coefficients, rc[k], can be computed using a simple Levinson
+ recurrence, initialized with the LPC coefficients
+ a[d_LPC-1][n]&nbsp;=&nbsp;a[n], and then updated via
+<figure align="center">
+<artwork align="center"><![CDATA[
+    rc[k] = -a[k][k] ,
+
+            a[k][n] - a[k][k-n-1]*rc[k]
+a[k-1][n] = --------------------------- .
+                             2
+                    1 - rc[k]
+]]></artwork>
+</figure>
+</t>
+<t>
+However, silk_LPC_inverse_pred_gain_QA() approximates this using fixed-point
+ arithmetic to guarantee reproducible results across platforms and
+ implementations.
+Since small changes in the coefficients can make a stable filter unstable, it
+ takes the real Q12 coefficients that will be used during reconstruction as
+ input.
+Thus, let
+<figure align="center">
+<artwork align="center"><![CDATA[
+a32_Q12[n] = (a32_Q17[n] + 16) >> 5
+]]></artwork>
+</figure>
+ be the Q12 version of the LPC coefficients that will eventually be used.
+As a simple initial check, the decoder computes the DC response as
+<figure align="center">
+<artwork align="center"><![CDATA[
+        d_PLC-1
+          __
+DC_resp = \   a32_Q12[n]
+          /_
+          n=0
+]]></artwork>
+</figure>
+ and if DC_resp&nbsp;&gt;&nbsp;4096, the filter is unstable.
+</t>
+<t>
+Increasing the precision of these Q12 coefficients to Q24 for intermediate
+ computations allows more accurate computation of the reflection coefficients,
+ so the decoder initializes the recurrence via
+<figure align="center">
+<artwork align="center"><![CDATA[
+a32_Q24[d_LPC-1][n] = a32_Q12[n] << 12 .
+]]></artwork>
+</figure>
+Then for each k from d_LPC-1 down to 0, if
+ abs(a32_Q24[k][k])&nbsp;&gt;&nbsp;16773022, the filter is unstable and the
+ recurrence stops.
+The constant 16773022 here is approximately 0.99975 in Q24.
+Otherwise, row k-1 of a32_Q24 is computed from row k as
+<figure align="center">
+<artwork align="center"><![CDATA[
+      rc_Q31[k] = -a32_Q24[k][k] << 7 ,
+
+     div_Q30[k] = (1<<30) - (rc_Q31[k]*rc_Q31[k] >> 32) ,
+
+          b1[k] = ilog(div_Q30[k]) ,
+
+          b2[k] = b1[k] - 16 ,
+
+                        (1<<29) - 1
+     inv_Qb2[k] = ----------------------- ,
+                  div_Q30[k] >> (b2[k]+1)
+
+     err_Q29[k] = (1<<29)
+                  - ((div_Q30[k]<<(15-b2[k]))*inv_Qb2[k] >> 16) ,
+
+    gain_Qb1[k] = ((inv_Qb2[k] << 16)
+                   + (err_Q29[k]*inv_Qb2[k] >> 13)) ,
+
+num_Q24[k-1][n] = a32_Q24[k][n]
+                  - ((a32_Q24[k][k-n-1]*rc_Q31[k] + (1<<30)) >> 31) ,
+
+a32_Q24[k-1][n] = (num_Q24[k-1][n]*gain_Qb1[k]
+                   + (1<<(b1[k]-1))) >> b1[k] ,
+]]></artwork>
+</figure>
+ where 0&nbsp;&lt;=&nbsp;n&nbsp;&lt;&nbsp;k.
+Here, rc_Q30[k] are the reflection coefficients.
+div_Q30[k] is the denominator for each iteration, and gain_Qb1[k] is its
+ multiplicative inverse (with b1[k] fractional bits, where b1[k] ranges from
+ 20 to 31).
+inv_Qb2[k], which ranges from 16384 to 32767, is a low-precision version of
+ that inverse (with b2[k] fractional bits).
+err_Q29[k] is the residual error, ranging from -32763 to 32392, which is used
+ to improve the accuracy.
+The values t_Q24[k-1][n] for each n are the numerators for the next row of
+ coefficients in the recursion, and a32_Q24[k-1][n] is the final version of
+ that row.
+Every multiply in this procedure except the one used to compute gain_Qb1[k]
+ requires more than 32 bits of precision, but otherwise all intermediate
+ results fit in 32 bits or less.
+In practice, because each row only depends on the next one, an implementation
+ does not need to store them all.
+</t>
+<t>
+If abs(a32_Q24[k][k])&nbsp;&lt;=&nbsp;16773022 for
+ 0&nbsp;&lt;=&nbsp;k&nbsp;&lt;&nbsp;d_LPC, then the filter is considered stable.
+However, the problem of determining stability is ill-conditioned when the
+ filter contains several reflection coefficients whose magnitude is very close
+ to one.
+This fixed-point algorithm is not mathematically guaranteed to correctly
+ classify filters as stable or unstable in this case, though it does very well
+ in practice.
+</t>
+<t>
+On round i, 1&nbsp;&lt;=&nbsp;i&nbsp;&lt;=&nbsp;18, if the filter passes these
+ stability checks, then this procedure stops, and the final LPC coefficients to
+ use for reconstruction in <xref target="silk_lpc_synthesis"/> are
+<figure align="center">
+<artwork align="center"><![CDATA[
+a_Q12[k] = (a32_Q17[k] + 16) >> 5 .
+]]></artwork>
+</figure>
+Otherwise, a round of bandwidth expansion is applied using the same procedure
+ as in <xref target="silk_lpc_range_limit"/>, with
+<figure align="center">
+<artwork align="center"><![CDATA[
+sc_Q16[0] = 65536 - (2<<i) .
+]]></artwork>
+</figure>
+During the 15th round, sc_Q16[0] becomes 0 in the above equation, so a_Q12[k]
+ is set to 0 for all k, guaranteeing a stable filter.
+</t>
+</section>
+
+</section>
+
+<section anchor="silk_ltp_params" toc="include"
+ title="Long-Term Prediction (LTP) Parameters">
+<t>
+After the normalized LSF indices and, for 20&nbsp;ms frames, the LSF
+ interpolation index, voiced frames (see <xref target="silk_frame_type"/>)
+ include additional LTP parameters.
+There is one primary lag index for each SILK frame, but this is refined to
+ produce a separate lag index per subframe using a vector quantizer.
+Each subframe also gets its own prediction gain coefficient.
+</t>
+
+<section anchor="silk_ltp_lags" title="Pitch Lags">
+<t>
+The primary lag index is coded either relative to the primary lag of the prior
+ frame in the same channel, or as an absolute index.
+Absolute coding is used if and only if
+<list style="symbols">
+<t>
+This is the first SILK frame of its type (LBRR or regular) for this channel in
+ the current Opus frame,
+</t>
+<t>
+The previous SILK frame of the same type (LBRR or regular) for this channel in
+ the same Opus frame was not coded, or
+</t>
+<t>
+That previous SILK frame was coded, but was not voiced (see
+ <xref target="silk_frame_type"/>).
+</t>
+</list>
+</t>
+
+<t>
+With absolute coding, the primary pitch lag may range from 2&nbsp;ms
+ (inclusive) up to 18&nbsp;ms (exclusive), corresponding to pitches from
+ 500&nbsp;Hz down to 55.6&nbsp;Hz, respectively.
+It is comprised of a high part and a low part, where the decoder reads the high
+ part using the 32-entry codebook in <xref target="silk_abs_pitch_high_pdf"/>
+ and the low part using the codebook corresponding to the current audio
+ bandwidth from <xref target="silk_abs_pitch_low_pdf"/>.
+The final primary pitch lag is then
+<figure align="center">
+<artwork align="center"><![CDATA[
+lag = lag_high*lag_scale + lag_low + lag_min
+]]></artwork>
+</figure>
+ where lag_high is the high part, lag_low is the low part, and lag_scale
+ and lag_min are the values from the "Scale" and "Minimum Lag" columns of
+ <xref target="silk_abs_pitch_low_pdf"/>, respectively.
+</t>
+
+<texttable anchor="silk_abs_pitch_high_pdf"
+ title="PDF for High Part of Primary Pitch Lag">
+<ttcol align="left">PDF</ttcol>
+<c>{3,   3,   6,  11,  21,  30,  32,  19,
+   11,  10,  12,  13,  13,  12,  11,   9,
+    8,   7,   6,   4,   2,   2,   2,   1,
+    1,   1,   1,   1,   1,   1,   1,   1}/256</c>
+</texttable>
+
+<texttable anchor="silk_abs_pitch_low_pdf"
+ title="PDF for Low Part of Primary Pitch Lag">
+<ttcol>Audio Bandwidth</ttcol>
+<ttcol>PDF</ttcol>
+<ttcol>Scale</ttcol>
+<ttcol>Minimum Lag</ttcol>
+<ttcol>Maximum Lag</ttcol>
+<c>NB</c> <c>{64, 64, 64, 64}/256</c>                 <c>4</c> <c>16</c> <c>144</c>
+<c>MB</c> <c>{43, 42, 43, 43, 42, 43}/256</c>         <c>6</c> <c>24</c> <c>216</c>
+<c>WB</c> <c>{32, 32, 32, 32, 32, 32, 32, 32}/256</c> <c>8</c> <c>32</c> <c>288</c>
+</texttable>
+
+<t>
+All frames that do not use absolute coding for the primary lag index use
+ relative coding instead.
+The decoder reads a single delta value using the 21-entry PDF in
+ <xref target="silk_rel_pitch_pdf"/>.
+If the resulting value is zero, it falls back to the absolute coding procedure
+ from the prior paragraph.
+Otherwise, the final primary pitch lag is then
+<figure align="center">
+<artwork align="center"><![CDATA[
+lag = previous_lag + (delta_lag_index - 9)
+]]></artwork>
+</figure>
+ where previous_lag is the primary pitch lag from the most recent frame in the
+ same channel and delta_lag_index is the value just decoded.
+This allows a per-frame change in the pitch lag of -8 to +11 samples.
+The decoder does no clamping at this point, so this value can fall outside the
+ range of 2&nbsp;ms to 18&nbsp;ms, and the decoder must use this unclamped
+ value when using relative coding in the next SILK frame (if any).
+However, because an Opus frame can use relative coding for at most two
+ consecutive SILK frames, integer overflow should not be an issue.
+</t>
+
+<texttable anchor="silk_rel_pitch_pdf"
+ title="PDF for Primary Pitch Lag Change">
+<ttcol align="left">PDF</ttcol>
+<c>{46,  2,  2,  3,  4,  6, 10, 15,
+    26, 38, 30, 22, 15, 10,  7,  6,
+     4,  4,  2,  2,  2}/256</c>
+</texttable>
+
+<t>
+After the primary pitch lag, a "pitch contour", stored as a single entry from
+ one of four small VQ codebooks, gives lag offsets for each subframe in the
+ current SILK frame.
+The codebook index is decoded using one of the PDFs in
+ <xref target="silk_pitch_contour_pdfs"/> depending on the current frame size
+ and audio bandwidth.
+Tables&nbsp;<xref format="counter" target="silk_pitch_contour_cb_nb10ms"/>
+ through&nbsp;<xref format="counter" target="silk_pitch_contour_cb_mbwb20ms"/>
+ give the corresponding offsets to apply to the primary pitch lag for each
+ subframe given the decoded codebook index.
+</t>
+
+<texttable anchor="silk_pitch_contour_pdfs"
+ title="PDFs for Subframe Pitch Contour">
+<ttcol>Audio Bandwidth</ttcol>
+<ttcol>SILK Frame Size</ttcol>
+<ttcol align="right">Codebook Size</ttcol>
+<ttcol>PDF</ttcol>
+<c>NB</c>       <c>10&nbsp;ms</c>  <c>3</c>
+<c>{143, 50, 63}/256</c>
+<c>NB</c>       <c>20&nbsp;ms</c> <c>11</c>
+<c>{68, 12, 21, 17, 19, 22, 30, 24,
+    17, 16, 10}/256</c>
+<c>MB or WB</c> <c>10&nbsp;ms</c> <c>12</c>
+<c>{91, 46, 39, 19, 14, 12,  8,  7,
+     6,  5,  5,  4}/256</c>
+<c>MB or WB</c> <c>20&nbsp;ms</c> <c>34</c>
+<c>{33, 22, 18, 16, 15, 14, 14, 13,
+    13, 10,  9,  9,  8,  6,  6,  6,
+     5,  4,  4,  4,  3,  3,  3,  2,
+     2,  2,  2,  2,  2,  2,  1,  1,
+     1,  1}/256</c>
+</texttable>
+
+<texttable anchor="silk_pitch_contour_cb_nb10ms"
+ title="Codebook Vectors for Subframe Pitch Contour: NB, 10&nbsp;ms Frames">
+<ttcol>Index</ttcol>
+<ttcol align="right">Subframe Offsets</ttcol>
+<c>0</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0</spanx></c>
+<c>1</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;0</spanx></c>
+<c>2</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;1</spanx></c>
+</texttable>
+
+<texttable anchor="silk_pitch_contour_cb_nb20ms"
+ title="Codebook Vectors for Subframe Pitch Contour: NB, 20&nbsp;ms Frames">
+<ttcol>Index</ttcol>
+<ttcol align="right">Subframe Offsets</ttcol>
+ <c>0</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>1</c> <c><spanx style="vbare">&nbsp;2&nbsp;&nbsp;1&nbsp;&nbsp;0&nbsp;-1</spanx></c>
+ <c>2</c> <c><spanx style="vbare">-1&nbsp;&nbsp;0&nbsp;&nbsp;1&nbsp;&nbsp;2</spanx></c>
+ <c>3</c> <c><spanx style="vbare">-1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;1</spanx></c>
+ <c>4</c> <c><spanx style="vbare">-1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>5</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;1</spanx></c>
+ <c>6</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;1&nbsp;&nbsp;1</spanx></c>
+ <c>7</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;1&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>8</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>9</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;-1</spanx></c>
+<c>10</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;-1</spanx></c>
+</texttable>
+
+<texttable anchor="silk_pitch_contour_cb_mbwb10ms"
+ title="Codebook Vectors for Subframe Pitch Contour: MB or WB, 10&nbsp;ms Frames">
+<ttcol>Index</ttcol>
+<ttcol align="right">Subframe Offsets</ttcol>
+ <c>0</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>1</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;1</spanx></c>
+ <c>2</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;0</spanx></c>
+ <c>3</c> <c><spanx style="vbare">-1&nbsp;&nbsp;1</spanx></c>
+ <c>4</c> <c><spanx style="vbare">&nbsp;1&nbsp;-1</spanx></c>
+ <c>5</c> <c><spanx style="vbare">-1&nbsp;&nbsp;2</spanx></c>
+ <c>6</c> <c><spanx style="vbare">&nbsp;2&nbsp;-1</spanx></c>
+ <c>7</c> <c><spanx style="vbare">-2&nbsp;&nbsp;2</spanx></c>
+ <c>8</c> <c><spanx style="vbare">&nbsp;2&nbsp;-2</spanx></c>
+ <c>9</c> <c><spanx style="vbare">-2&nbsp;&nbsp;3</spanx></c>
+<c>10</c> <c><spanx style="vbare">&nbsp;3&nbsp;-2</spanx></c>
+<c>11</c> <c><spanx style="vbare">-3&nbsp;&nbsp;3</spanx></c>
+</texttable>
+
+<texttable anchor="silk_pitch_contour_cb_mbwb20ms"
+ title="Codebook Vectors for Subframe Pitch Contour: MB or WB, 20&nbsp;ms Frames">
+<ttcol>Index</ttcol>
+<ttcol align="right">Subframe Offsets</ttcol>
+ <c>0</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>1</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;1&nbsp;&nbsp;1</spanx></c>
+ <c>2</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;1&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>3</c> <c><spanx style="vbare">-1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>4</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;1</spanx></c>
+ <c>5</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0</spanx></c>
+ <c>6</c> <c><spanx style="vbare">-1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;1</spanx></c>
+ <c>7</c> <c><spanx style="vbare">&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;-1</spanx></c>
+ <c>8</c> <c><spanx style="vbare">-1&nbsp;&nbsp;0&nbsp;&nbsp;1&nbsp;&nbsp;2</spanx></c>
+ <c>9</c> <c><spanx style="vbare">&nbsp;1&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;-1</spanx></c>
+<c>10</c> <c><spanx style="vbare">-2&nbsp;-1&nbsp;&nbsp;1&nbsp;&nbsp;2</spanx></c>
+<c>11</c> <c><spanx style="vbare">&nbsp;2&nbsp;&nbsp;1&nbsp;&nbsp;0&nbsp;-1</spanx></c>
+<c>12</c> <c><spanx style="vbare">-2&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;&nbsp;2</spanx></c>
+<c>13</c> <c><spanx style="vbare">-2&nbsp;&nbsp;0&nbsp;&nbsp;1&nbsp;&nbsp;3</spanx></c>
+<c>14</c> <c><spanx style="vbare">&nbsp;2&nbsp;&nbsp;1&nbsp;-1&nbsp;-2</spanx></c>
+<c>15</c> <c><spanx style="vbare">-3&nbsp;-1&nbsp;&nbsp;1&nbsp;&nbsp;3</spanx></c>
+<c>16</c> <c><spanx style="vbare">&nbsp;2&nbsp;&nbsp;0&nbsp;&nbsp;0&nbsp;-2</spanx></c>
+<c>17</c> <c><spanx style="vbare">&nbsp;3&nbsp;&nbsp;1&nbsp;&nbsp;0&nbsp;-2</spanx></c>
+<c>18</c> <c><spanx style="vbare">-3&nbsp;-1&nbsp;&nbsp;2&nbsp;&nbsp;4</spanx></c>
+<c>19</c> <c><spanx style="vbare">-4&nbsp;-1&nbsp;&nbsp;1&nbsp;&nbsp;4</spanx></c>
+<c>20</c> <c><spanx style="vbare">&nbsp;3&nbsp;&nbsp;1&nbsp;-1&nbsp;-3</spanx></c>
+<c>21</c> <c><spanx style="vbare">-4&nbsp;-1&nbsp;&nbsp;2&nbsp;&nbsp;5</spanx></c>
+<c>22</c> <c><spanx style="vbare">&nbsp;4&nbsp;&nbsp;2&nbsp;-1&nbsp;-3</spanx></c>
+<c>23</c> <c><spanx style="vbare">&nbsp;4&nbsp;&nbsp;1&nbsp;-1&nbsp;-4</spanx></c>
+<c>24</c> <c><spanx style="vbare">-5&nbsp;-1&nbsp;&nbsp;2&nbsp;&nbsp;6</spanx></c>
+<c>25</c> <c><spanx style="vbare">&nbsp;5&nbsp;&nbsp;2&nbsp;-1&nbsp;-4</spanx></c>
+<c>26</c> <c><spanx style="vbare">-6&nbsp;-2&nbsp;&nbsp;2&nbsp;&nbsp;6</spanx></c>
+<c>27</c> <c><spanx style="vbare">-5&nbsp;-2&nbsp;&nbsp;2&nbsp;&nbsp;5</spanx></c>
+<c>28</c> <c><spanx style="vbare">&nbsp;6&nbsp;&nbsp;2&nbsp;-1&nbsp;-5</spanx></c>
+<c>29</c> <c><spanx style="vbare">-7&nbsp;-2&nbsp;&nbsp;3&nbsp;&nbsp;8</spanx></c>
+<c>30</c> <c><spanx style="vbare">&nbsp;6&nbsp;&nbsp;2&nbsp;-2&nbsp;-6</spanx></c>
+<c>31</c> <c><spanx style="vbare">&nbsp;5&nbsp;&nbsp;2&nbsp;-2&nbsp;-5</spanx></c>
+<c>32</c> <c><spanx style="vbare">&nbsp;8&nbsp;&nbsp;3&nbsp;-2&nbsp;-7</spanx></c>
+<c>33</c> <c><spanx style="vbare">-9&nbsp;-3&nbsp;&nbsp;3&nbsp;&nbsp;9</spanx></c>
+</texttable>
+
+<t>
+The final pitch lag for each subframe is assembled in silk_decode_pitch()
+ (decode_pitch.c).
+Let lag be the primary pitch lag for the current SILK frame, contour_index be
+ index of the VQ codebook, and lag_cb[contour_index][k] be the corresponding
+ entry of the codebook from the appropriate table given above for the k'th
+ subframe.
+Then the final pitch lag for that subframe is
+<figure align="center">
+<artwork align="center"><![CDATA[
+pitch_lags[k] = clamp(lag_min, lag + lag_cb[contour_index][k],
+                      lag_max)
+]]></artwork>
+</figure>
+ where lag_min and lag_max are the values from the "Minimum Lag" and
+ "Maximum Lag" columns of <xref target="silk_abs_pitch_low_pdf"/>,
+ respectively.
+</t>
+
+</section>
+
+<section anchor="silk_ltp_filter" title="LTP Filter Coefficients">
+<t>
+SILK uses a separate 5-tap pitch filter for each subframe, selected from one
+ of three codebooks.
+The three codebooks each represent different rate-distortion trade-offs, with
+ average rates of 1.61&nbsp;bits/subframe, 3.68&nbsp;bits/subframe, and
+ 4.85&nbsp;bits/subframe, respectively.
+</t>
+
+<t>
+The importance of the filter coefficients generally depends on two factors: the
+ periodicity of the signal and relative energy between the current subframe and
+ the signal from one period earlier.
+Greater periodicity and decaying energy both lead to more important filter
+ coefficients, and thus should be coded with lower distortion and higher rate.
+These properties are relatively stable over the duration of a single SILK
+ frame, hence all of the subframes in a SILK frame choose their filter from the
+ same codebook.
+This is signaled with an explicitly-coded "periodicity index".
+This immediately follows the subframe pitch lags, and is coded using the
+ 3-entry PDF from <xref target="silk_perindex_pdf"/>.
+</t>
+
+<texttable anchor="silk_perindex_pdf" title="Periodicity Index PDF">
+<ttcol>PDF</ttcol>
+<c>{77, 80, 99}/256</c>
+</texttable>
+
+<t>
+The indices of the filters for each subframe follow.
+They are all coded using the PDF from <xref target="silk_ltp_filter_pdfs"/>
+ corresponding to the periodicity index.
+Tables&nbsp;<xref format="counter" target="silk_ltp_filter_coeffs0"/>
+ through&nbsp;<xref format="counter" target="silk_ltp_filter_coeffs2"/>
+ contain the corresponding filter taps as signed Q7 integers.
+</t>
+
+<texttable anchor="silk_ltp_filter_pdfs" title="LTP Filter PDFs">
+<ttcol>Periodicity Index</ttcol>
+<ttcol align="right">Codebook Size</ttcol>
+<ttcol>PDF</ttcol>
+<c>0</c>  <c>8</c> <c>{185, 15, 13, 13, 9, 9, 6, 6}/256</c>
+<c>1</c> <c>16</c> <c>{57, 34, 21, 20, 15, 13, 12, 13,
+                       10, 10,  9, 10,  9,  8,  7,  8}/256</c>
+<c>2</c> <c>32</c> <c>{15, 16, 14, 12, 12, 12, 11, 11,
+                       11, 10,  9,  9,  9,  9,  8,  8,
+                        8,  8,  7,  7,  6,  6,  5,  4,
+                        5,  4,  4,  4,  3,  4,  3,  2}/256</c>
+</texttable>
+
+<texttable anchor="silk_ltp_filter_coeffs0"
+ title="Codebook Vectors for LTP Filter, Periodicity Index 0">
+<ttcol>Index</ttcol>
+<ttcol align="right">Filter Taps (Q7)</ttcol>
+ <c>0</c>
+<c><spanx style="vbare">&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;24&nbsp;&nbsp;&nbsp;7&nbsp;&nbsp;&nbsp;5</spanx></c>
+ <c>1</c>
+<c><spanx style="vbare">&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;0</spanx></c>
+ <c>2</c>
+<c><spanx style="vbare">&nbsp;12&nbsp;&nbsp;28&nbsp;&nbsp;41&nbsp;&nbsp;13&nbsp;&nbsp;-4</spanx></c>
+ <c>3</c>
+<c><spanx style="vbare">&nbsp;-9&nbsp;&nbsp;15&nbsp;&nbsp;42&nbsp;&nbsp;25&nbsp;&nbsp;14</spanx></c>
+ <c>4</c>
+<c><spanx style="vbare">&nbsp;&nbsp;1&nbsp;&nbsp;-2&nbsp;&nbsp;62&nbsp;&nbsp;41&nbsp;&nbsp;-9</spanx></c>
+ <c>5</c>
+<c><spanx style="vbare">-10&nbsp;&nbsp;37&nbsp;&nbsp;65&nbsp;&nbsp;-4&nbsp;&nbsp;&nbsp;3</spanx></c>
+ <c>6</c>
+<c><spanx style="vbare">&nbsp;-6&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;66&nbsp;&nbsp;&nbsp;7&nbsp;&nbsp;-8</spanx></c>
+ <c>7</c>
+<c><spanx style="vbare">&nbsp;16&nbsp;&nbsp;14&nbsp;&nbsp;38&nbsp;&nbsp;-3&nbsp;&nbsp;33</spanx></c>
+</texttable>
+
+<texttable anchor="silk_ltp_filter_coeffs1"
+ title="Codebook Vectors for LTP Filter, Periodicity Index 1">
+<ttcol>Index</ttcol>
+<ttcol align="right">Filter Taps (Q7)</ttcol>
+
+ <c>0</c>
+<c><spanx style="vbare">&nbsp;13&nbsp;&nbsp;22&nbsp;&nbsp;39&nbsp;&nbsp;23&nbsp;&nbsp;12</spanx></c>
+ <c>1</c>
+<c><spanx style="vbare">&nbsp;-1&nbsp;&nbsp;36&nbsp;&nbsp;64&nbsp;&nbsp;27&nbsp;&nbsp;-6</spanx></c>
+ <c>2</c>
+<c><spanx style="vbare">&nbsp;-7&nbsp;&nbsp;10&nbsp;&nbsp;55&nbsp;&nbsp;43&nbsp;&nbsp;17</spanx></c>
+ <c>3</c>
+<c><spanx style="vbare">&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;8&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;1</spanx></c>
+ <c>4</c>
+<c><spanx style="vbare">&nbsp;&nbsp;6&nbsp;-11&nbsp;&nbsp;74&nbsp;&nbsp;53&nbsp;&nbsp;-9</spanx></c>
+ <c>5</c>
+<c><spanx style="vbare">-12&nbsp;&nbsp;55&nbsp;&nbsp;76&nbsp;-12&nbsp;&nbsp;&nbsp;8</spanx></c>
+ <c>6</c>
+<c><spanx style="vbare">&nbsp;-3&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;93&nbsp;&nbsp;27&nbsp;&nbsp;-4</spanx></c>
+ <c>7</c>
+<c><spanx style="vbare">&nbsp;26&nbsp;&nbsp;39&nbsp;&nbsp;59&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;-8</spanx></c>
+ <c>8</c>
+<c><spanx style="vbare">&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;77&nbsp;&nbsp;11&nbsp;&nbsp;&nbsp;9</spanx></c>
+ <c>9</c>
+<c><spanx style="vbare">&nbsp;-8&nbsp;&nbsp;22&nbsp;&nbsp;44&nbsp;&nbsp;-6&nbsp;&nbsp;&nbsp;7</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">&nbsp;40&nbsp;&nbsp;&nbsp;9&nbsp;&nbsp;26&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;9</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">&nbsp;-7&nbsp;&nbsp;20&nbsp;101&nbsp;&nbsp;-7&nbsp;&nbsp;&nbsp;4</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">&nbsp;&nbsp;3&nbsp;&nbsp;-8&nbsp;&nbsp;42&nbsp;&nbsp;26&nbsp;&nbsp;&nbsp;0</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">-15&nbsp;&nbsp;33&nbsp;&nbsp;68&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;23</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">&nbsp;-2&nbsp;&nbsp;55&nbsp;&nbsp;46&nbsp;&nbsp;-2&nbsp;&nbsp;15</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">&nbsp;&nbsp;3&nbsp;&nbsp;-1&nbsp;&nbsp;21&nbsp;&nbsp;16&nbsp;&nbsp;41</spanx></c>
+</texttable>
+
+<texttable anchor="silk_ltp_filter_coeffs2"
+ title="Codebook Vectors for LTP Filter, Periodicity Index 2">
+<ttcol>Index</ttcol>
+<ttcol align="right">Filter Taps (Q7)</ttcol>
+ <c>0</c>
+<c><spanx style="vbare">&nbsp;-6&nbsp;&nbsp;27&nbsp;&nbsp;61&nbsp;&nbsp;39&nbsp;&nbsp;&nbsp;5</spanx></c>
+ <c>1</c>
+<c><spanx style="vbare">-11&nbsp;&nbsp;42&nbsp;&nbsp;88&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;1</spanx></c>
+ <c>2</c>
+<c><spanx style="vbare">&nbsp;-2&nbsp;&nbsp;60&nbsp;&nbsp;65&nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;-4</spanx></c>
+ <c>3</c>
+<c><spanx style="vbare">&nbsp;-1&nbsp;&nbsp;-5&nbsp;&nbsp;73&nbsp;&nbsp;56&nbsp;&nbsp;&nbsp;1</spanx></c>
+ <c>4</c>
+<c><spanx style="vbare">&nbsp;-9&nbsp;&nbsp;19&nbsp;&nbsp;94&nbsp;&nbsp;29&nbsp;&nbsp;-9</spanx></c>
+ <c>5</c>
+<c><spanx style="vbare">&nbsp;&nbsp;0&nbsp;&nbsp;12&nbsp;&nbsp;99&nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;&nbsp;4</spanx></c>
+ <c>6</c>
+<c><spanx style="vbare">&nbsp;&nbsp;8&nbsp;-19&nbsp;102&nbsp;&nbsp;46&nbsp;-13</spanx></c>
+ <c>7</c>
+<c><spanx style="vbare">&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;13&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;2</spanx></c>
+ <c>8</c>
+<c><spanx style="vbare">&nbsp;&nbsp;9&nbsp;-21&nbsp;&nbsp;84&nbsp;&nbsp;72&nbsp;-18</spanx></c>
+ <c>9</c>
+<c><spanx style="vbare">-11&nbsp;&nbsp;46&nbsp;104&nbsp;-22&nbsp;&nbsp;&nbsp;8</spanx></c>
+<c>10</c>
+<c><spanx style="vbare">&nbsp;18&nbsp;&nbsp;38&nbsp;&nbsp;48&nbsp;&nbsp;23&nbsp;&nbsp;&nbsp;0</spanx></c>
+<c>11</c>
+<c><spanx style="vbare">-16&nbsp;&nbsp;70&nbsp;&nbsp;83&nbsp;-21&nbsp;&nbsp;11</spanx></c>
+<c>12</c>
+<c><spanx style="vbare">&nbsp;&nbsp;5&nbsp;-11&nbsp;117&nbsp;&nbsp;22&nbsp;&nbsp;-8</spanx></c>
+<c>13</c>
+<c><spanx style="vbare">&nbsp;-6&nbsp;&nbsp;23&nbsp;117&nbsp;-12&nbsp;&nbsp;&nbsp;3</spanx></c>
+<c>14</c>
+<c><spanx style="vbare">&nbsp;&nbsp;3&nbsp;&nbsp;-8&nbsp;&nbsp;95&nbsp;&nbsp;28&nbsp;&nbsp;&nbsp;4</spanx></c>
+<c>15</c>
+<c><spanx style="vbare">-10&nbsp;&nbsp;15&nbsp;&nbsp;77&nbsp;&nbsp;60&nbsp;-15</spanx></c>
+<c>16</c>
+<c><spanx style="vbare">&nbsp;-1&nbsp;&nbsp;&nbsp;4&nbsp;124&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;-4</spanx></c>
+<c>17</c>
+<c><spanx style="vbare">&nbsp;&nbsp;3&nbsp;&nbsp;38&nbsp;&nbsp;84&nbsp;&nbsp;24&nbsp;-25</spanx></c>
+<c>18</c>
+<c><spanx style="vbare">&nbsp;&nbsp;2&nbsp;&nbsp;13&nbsp;&nbsp;42&nbsp;&nbsp;13&nbsp;&nbsp;31</spanx></c>
+<c>19</c>
+<c><spanx style="vbare">&nbsp;21&nbsp;&nbsp;-4&nbsp;&nbsp;56&nbsp;&nbsp;46&nbsp;&nbsp;-1</spanx></c>
+<c>20</c>
+<c><spanx style="vbare">&nbsp;-1&nbsp;&nbsp;35&nbsp;&nbsp;79&nbsp;-13&nbsp;&nbsp;19</spanx></c>
+<c>21</c>
+<c><spanx style="vbare">&nbsp;-7&nbsp;&nbsp;65&nbsp;&nbsp;88&nbsp;&nbsp;-9&nbsp;-14</spanx></c>
+<c>22</c>
+<c><spanx style="vbare">&nbsp;20&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;81&nbsp;&nbsp;49&nbsp;-29</spanx></c>
+<c>23</c>
+<c><spanx style="vbare">&nbsp;20&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;75&nbsp;&nbsp;&nbsp;3&nbsp;-17</spanx></c>
+<c>24</c>
+<c><spanx style="vbare">&nbsp;&nbsp;5&nbsp;&nbsp;-9&nbsp;&nbsp;44&nbsp;&nbsp;92&nbsp;&nbsp;-8</spanx></c>
+<c>25</c>
+<c><spanx style="vbare">&nbsp;&nbsp;1&nbsp;&nbsp;-3&nbsp;&nbsp;22&nbsp;&nbsp;69&nbsp;&nbsp;31</spanx></c>
+<c>26</c>
+<c><spanx style="vbare">&nbsp;-6&nbsp;&nbsp;95&nbsp;&nbsp;41&nbsp;-12&nbsp;&nbsp;&nbsp;5</spanx></c>
+<c>27</c>
+<c><spanx style="vbare">&nbsp;39&nbsp;&nbsp;67&nbsp;&nbsp;16&nbsp;&nbsp;-4&nbsp;&nbsp;&nbsp;1</spanx></c>
+<c>28</c>
+<c><spanx style="vbare">&nbsp;&nbsp;0&nbsp;&nbsp;-6&nbsp;120&nbsp;&nbsp;55&nbsp;-36</spanx></c>
+<c>29</c>
+<c><spanx style="vbare">-13&nbsp;&nbsp;44&nbsp;122&nbsp;&nbsp;&nbsp;4&nbsp;-24</spanx></c>
+<c>30</c>
+<c><spanx style="vbare">&nbsp;81&nbsp;&nbsp;&nbsp;5&nbsp;&nbsp;11&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;7</spanx></c>
+<c>31</c>
+<c><spanx style="vbare">&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;9&nbsp;&nbsp;10&nbsp;&nbsp;88</spanx></c>
+</texttable>
+
+</section>
+
+<section anchor="silk_ltp_scaling" title="LTP Scaling Parameter">
+<t>
+An LTP scaling parameter appears after the LTP filter coefficients if and only
+ if
+<list style="symbols">
+<t>This is a voiced frame (see <xref target="silk_frame_type"/>), and</t>
+<t>Either
+<list style="symbols">
+<t>
+This SILK frame corresponds to the first time interval of the
+ current Opus frame for its type (LBRR or regular), or
+</t>
+<t>
+This is an LBRR frame where the LBRR flags (see
+ <xref target="silk_lbrr_flags"/>) indicate the previous LBRR frame in the same
+ channel is not coded.
+</t>
+</list>
+</t>
+</list>
+This allows the encoder to trade off the prediction gain between
+ packets against the recovery time after packet loss.
+Unlike absolute-coding for pitch lags, regular SILK frames that are not at the
+ start of an Opus frame (i.e., that do not correspond to the first 20&nbsp;ms
+ time interval in Opus frames of 40&nbsp;or 60&nbsp;ms) do not include this
+ field, even if the prior frame was not voiced, or (in the case of the side
+ channel) not even coded.
+After an uncoded frame in the side channel, the LTP buffer (see
+ <xref target="silk_ltp_synthesis"/>) is cleared to zero, and is thus in a
+ known state.
+In contrast, LBRR frames do include this field when the prior frame was not
+ coded, since the LTP buffer contains the output of the PLC, which is
+ non-normative.
+</t>
+<t>
+If present, the decoder reads a value using the 3-entry PDF in
+ <xref target="silk_ltp_scaling_pdf"/>.
+The three possible values represent Q14 scale factors of 15565, 12288, and
+ 8192, respectively (corresponding to approximately 0.95, 0.75, and 0.5).
+Frames that do not code the scaling parameter use the default factor of 15565
+ (approximately 0.95).
+</t>
+
+<texttable anchor="silk_ltp_scaling_pdf"
+ title="PDF for LTP Scaling Parameter">
+<ttcol align="left">PDF</ttcol>
+<c>{128, 64, 64}/256</c>
+</texttable>
+
+</section>
+
+</section>
+
+<section anchor="silk_seed" toc="include"
+ title="Linear Congruential Generator (LCG) Seed">
+<t>
+As described in <xref target="silk_excitation_reconstruction"/>, SILK uses a
+ linear congruential generator (LCG) to inject pseudorandom noise into the
+ quantized excitation.
+To ensure synchronization of this process between the encoder and decoder, each
+ SILK frame stores a 2-bit seed after the LTP parameters (if any).
+The encoder may consider the choice of seed during quantization, and the
+ flexibility of this choice lets it reduce distortion, helping to pay for the
+ bit cost required to signal it.
+The decoder reads the seed using the uniform 4-entry PDF in
+ <xref target="silk_seed_pdf"/>, yielding a value between 0 and 3, inclusive.
+</t>
+
+<texttable anchor="silk_seed_pdf"
+ title="PDF for LCG Seed">
+<ttcol align="left">PDF</ttcol>
+<c>{64, 64, 64, 64}/256</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_excitation" toc="include" title="Excitation">
+<t>
+SILK codes the excitation using a modified version of the Pyramid Vector
+ Quantization (PVQ) codebook <xref target="PVQ"/>.
+The PVQ codebook is designed for Laplace-distributed values and consists of all
+ sums of K signed, unit pulses in a vector of dimension N, where two pulses at
+ the same position are required to have the same sign.
+Thus the codebook includes all integer codevectors y of dimension N that
+ satisfy
+<figure align="center">
+<artwork align="center"><![CDATA[
+N-1
+__
+\  abs(y[j]) = K .
+/_
+j=0
+]]></artwork>
+</figure>
+Unlike regular PVQ, SILK uses a variable-length, rather than fixed-length,
+ encoding.
+This encoding is better suited to the more Gaussian-like distribution of the
+ coefficient magnitudes and the non-uniform distribution of their signs (caused
+ by the quantization offset described below).
+SILK also handles large codebooks by coding the least significant bits (LSBs)
+ of each coefficient directly.
+This adds a small coding efficiency loss, but greatly reduces the computation
+ time and ROM size required for decoding, as implemented in
+ silk_decode_pulses() (decode_pulses.c).
+</t>
+
+<t>
+SILK fixes the dimension of the codebook to N&nbsp;=&nbsp;16.
+The excitation is made up of a number of "shell blocks", each 16 samples in
+ size.
+<xref target="silk_shell_block_table"/> lists the number of shell blocks
+ required for a SILK frame for each possible audio bandwidth and frame size.
+10&nbsp;ms MB frames nominally contain 120&nbsp;samples (10&nbsp;ms at
+ 12&nbsp;kHz), which is not a multiple of 16.
+This is handled by coding 8 shell blocks (128 samples) and discarding the final
+ 8 samples of the last block.
+The decoder contains no special case that prevents an encoder from placing
+ pulses in these samples, and they must be correctly parsed from the bitstream
+ if present, but they are otherwise ignored.
+</t>
+
+<texttable anchor="silk_shell_block_table"
+ title="Number of Shell Blocks Per SILK Frame">
+<ttcol>Audio Bandwidth</ttcol>
+<ttcol>Frame Size</ttcol>
+<ttcol align="right">Number of Shell Blocks</ttcol>
+<c>NB</c> <c>10&nbsp;ms</c>  <c>5</c>
+<c>MB</c> <c>10&nbsp;ms</c>  <c>8</c>
+<c>WB</c> <c>10&nbsp;ms</c> <c>10</c>
+<c>NB</c> <c>20&nbsp;ms</c> <c>10</c>
+<c>MB</c> <c>20&nbsp;ms</c> <c>15</c>
+<c>WB</c> <c>20&nbsp;ms</c> <c>20</c>
+</texttable>
+
+<section anchor="silk_rate_level" title="Rate Level">
+<t>
+The first symbol in the excitation is a "rate level", which is an index from 0
+ to 8, inclusive, coded using the PDF in <xref target="silk_rate_level_pdfs"/>
+ corresponding to the signal type of the current frame (from
+ <xref target="silk_frame_type"/>).
+The rate level selects the PDF used to decode the number of pulses in
+ the individual shell blocks.
+It does not directly convey any information about the bitrate or the number of
+ pulses itself, but merely changes the probability of the symbols in
+ <xref target="silk_pulse_counts"/>.
+Level&nbsp;0 provides a more efficient encoding at low rates generally, and
+ level&nbsp;8 provides a more efficient encoding at high rates generally,
+ though the most efficient level for a particular SILK frame may depend on the
+ exact distribution of the coded symbols.
+An encoder should, but is not required to, use the most efficient rate level.
+</t>
+
+<texttable anchor="silk_rate_level_pdfs"
+ title="PDFs for the Rate Level">
+<ttcol>Signal Type</ttcol>
+<ttcol>PDF</ttcol>
+<c>Inactive or Unvoiced</c>
+<c>{15, 51, 12, 46, 45, 13, 33, 27, 14}/256</c>
+<c>Voiced</c>
+<c>{33, 30, 36, 17, 34, 49, 18, 21, 18}/256</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_pulse_counts" title="Pulses Per Shell Block">
+<t>
+The total number of pulses in each of the shell blocks follows the rate level.
+The pulse counts for all of the shell blocks are coded consecutively, before
+ the content of any of the blocks.
+Each block may have anywhere from 0 to 16 pulses, inclusive, coded using the
+ 18-entry PDF in <xref target="silk_pulse_count_pdfs"/> corresponding to the
+ rate level from <xref target="silk_rate_level"/>.
+The special value 17 indicates that this block has one or more additional
+ LSBs to decode for each coefficient.
+If the decoder encounters this value, it decodes another value for the actual
+ pulse count of the block, but uses the PDF corresponding to the special rate
+ level&nbsp;9 instead of the normal rate level.
+This process repeats until the decoder reads a value less than 17, and it then
+ sets the number of extra LSBs used to the number of 17's decoded for that
+ block.
+If it reads the value 17 ten times, then the next iteration uses the special
+ rate level&nbsp;10 instead of 9.
+The probability of decoding a 17 when using the PDF for rate level&nbsp;10 is
+ zero, ensuring that the number of LSBs for a block will not exceed 10.
+The cumulative distribution for rate level&nbsp;10 is just a shifted version of
+ that for 9 and thus does not require any additional storage.
+</t>
+
+<texttable anchor="silk_pulse_count_pdfs"
+ title="PDFs for the Pulse Count">
+<ttcol>Rate Level</ttcol>
+<ttcol>PDF</ttcol>
+<c>0</c>
+<c>{131, 74, 25, 8, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}/256</c>
+<c>1</c>
+<c>{58, 93, 60, 23, 7, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}/256</c>
+<c>2</c>
+<c>{43, 51, 46, 33, 24, 16, 11, 8, 6, 3, 3, 3, 2, 1, 1, 2, 1, 2}/256</c>
+<c>3</c>
+<c>{17, 52, 71, 57, 31, 12, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}/256</c>
+<c>4</c>
+<c>{6, 21, 41, 53, 49, 35, 21, 11, 6, 3, 2, 2, 1, 1, 1, 1, 1, 1}/256</c>
+<c>5</c>
+<c>{7, 14, 22, 28, 29, 28, 25, 20, 17, 13, 11, 9, 7, 5, 4, 4, 3, 10}/256</c>
+<c>6</c>
+<c>{2, 5, 14, 29, 42, 46, 41, 31, 19, 11, 6, 3, 2, 1, 1, 1, 1, 1}/256</c>
+<c>7</c>
+<c>{1, 2, 4, 10, 19, 29, 35, 37, 34, 28, 20, 14, 8, 5, 4, 2, 2, 2}/256</c>
+<c>8</c>
+<c>{1, 2, 2, 5, 9, 14, 20, 24, 27, 28, 26, 23, 20, 15, 11, 8, 6, 15}/256</c>
+<c>9</c>
+<c>{1, 1, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2}/256</c>
+<c>10</c>
+<c>{2, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2, 0}/256</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_pulse_locations" title="Pulse Location Decoding">
+<t>
+The locations of the pulses in each shell block follow the pulse counts,
+ as decoded by silk_shell_decoder() (shell_coder.c).
+As with the pulse counts, these locations are coded for all the shell blocks
+ before any of the remaining information for each block.
+Unlike many other codecs, SILK places no restriction on the distribution of
+ pulses within a shell block.
+All of the pulses may be placed in a single location, or each one in a unique
+ location, or anything in between.
+</t>
+
+<t>
+The location of pulses is coded by recursively partitioning each block into
+ halves, and coding how many pulses fall on the left side of the split.
+All remaining pulses must fall on the right side of the split.
+The process then recurses into the left half, and after that returns, the
+ right half (preorder traversal).
+The PDF to use is chosen by the size of the current partition (16, 8, 4, or 2)
+ and the number of pulses in the partition (1 to 16, inclusive).
+Tables&nbsp;<xref format="counter" target="silk_shell_code3_pdfs"/>
+ through&nbsp;<xref format="counter" target="silk_shell_code0_pdfs"/> list the
+ PDFs used for each partition size and pulse count.
+This process skips partitions without any pulses, i.e., where the initial pulse
+ count from <xref target="silk_pulse_counts"/> was zero, or where the split in
+ the prior level indicated that all of the pulses fell on the other side.
+These partitions have nothing to code, so they require no PDF.
+</t>
+
+<texttable anchor="silk_shell_code3_pdfs"
+ title="PDFs for Pulse Count Split, 16 Sample Partitions">
+<ttcol>Pulse Count</ttcol>
+<ttcol>PDF</ttcol>
+ <c>1</c> <c>{126, 130}/256</c>
+ <c>2</c> <c>{56, 142, 58}/256</c>
+ <c>3</c> <c>{25, 101, 104, 26}/256</c>
+ <c>4</c> <c>{12, 60, 108, 64, 12}/256</c>
+ <c>5</c> <c>{7, 35, 84, 87, 37, 6}/256</c>
+ <c>6</c> <c>{4, 20, 59, 86, 63, 21, 3}/256</c>
+ <c>7</c> <c>{3, 12, 38, 72, 75, 42, 12, 2}/256</c>
+ <c>8</c> <c>{2, 8, 25, 54, 73, 59, 27, 7, 1}/256</c>
+ <c>9</c> <c>{2, 5, 17, 39, 63, 65, 42, 18, 4, 1}/256</c>
+<c>10</c> <c>{1, 4, 12, 28, 49, 63, 54, 30, 11, 3, 1}/256</c>
+<c>11</c> <c>{1, 4, 8, 20, 37, 55, 57, 41, 22, 8, 2, 1}/256</c>
+<c>12</c> <c>{1, 3, 7, 15, 28, 44, 53, 48, 33, 16, 6, 1, 1}/256</c>
+<c>13</c> <c>{1, 2, 6, 12, 21, 35, 47, 48, 40, 25, 12, 5, 1, 1}/256</c>
+<c>14</c> <c>{1, 1, 4, 10, 17, 27, 37, 47, 43, 33, 21, 9, 4, 1, 1}/256</c>
+<c>15</c> <c>{1, 1, 1, 8, 14, 22, 33, 40, 43, 38, 28, 16, 8, 1, 1, 1}/256</c>
+<c>16</c> <c>{1, 1, 1, 1, 13, 18, 27, 36, 41, 41, 34, 24, 14, 1, 1, 1, 1}/256</c>
+</texttable>
+
+<texttable anchor="silk_shell_code2_pdfs"
+ title="PDFs for Pulse Count Split, 8 Sample Partitions">
+<ttcol>Pulse Count</ttcol>
+<ttcol>PDF</ttcol>
+ <c>1</c> <c>{127, 129}/256</c>
+ <c>2</c> <c>{53, 149, 54}/256</c>
+ <c>3</c> <c>{22, 105, 106, 23}/256</c>
+ <c>4</c> <c>{11, 61, 111, 63, 10}/256</c>
+ <c>5</c> <c>{6, 35, 86, 88, 36, 5}/256</c>
+ <c>6</c> <c>{4, 20, 59, 87, 62, 21, 3}/256</c>
+ <c>7</c> <c>{3, 13, 40, 71, 73, 41, 13, 2}/256</c>
+ <c>8</c> <c>{3, 9, 27, 53, 70, 56, 28, 9, 1}/256</c>
+ <c>9</c> <c>{3, 8, 19, 37, 57, 61, 44, 20, 6, 1}/256</c>
+<c>10</c> <c>{3, 7, 15, 28, 44, 54, 49, 33, 17, 5, 1}/256</c>
+<c>11</c> <c>{1, 7, 13, 22, 34, 46, 48, 38, 28, 14, 4, 1}/256</c>
+<c>12</c> <c>{1, 1, 11, 22, 27, 35, 42, 47, 33, 25, 10, 1, 1}/256</c>
+<c>13</c> <c>{1, 1, 6, 14, 26, 37, 43, 43, 37, 26, 14, 6, 1, 1}/256</c>
+<c>14</c> <c>{1, 1, 4, 10, 20, 31, 40, 42, 40, 31, 20, 10, 4, 1, 1}/256</c>
+<c>15</c> <c>{1, 1, 3, 8, 16, 26, 35, 38, 38, 35, 26, 16, 8, 3, 1, 1}/256</c>
+<c>16</c> <c>{1, 1, 2, 6, 12, 21, 30, 36, 38, 36, 30, 21, 12, 6, 2, 1, 1}/256</c>
+</texttable>
+
+<texttable anchor="silk_shell_code1_pdfs"
+ title="PDFs for Pulse Count Split, 4 Sample Partitions">
+<ttcol>Pulse Count</ttcol>
+<ttcol>PDF</ttcol>
+ <c>1</c> <c>{127, 129}/256</c>
+ <c>2</c> <c>{49, 157, 50}/256</c>
+ <c>3</c> <c>{20, 107, 109, 20}/256</c>
+ <c>4</c> <c>{11, 60, 113, 62, 10}/256</c>
+ <c>5</c> <c>{7, 36, 84, 87, 36, 6}/256</c>
+ <c>6</c> <c>{6, 24, 57, 82, 60, 23, 4}/256</c>
+ <c>7</c> <c>{5, 18, 39, 64, 68, 42, 16, 4}/256</c>
+ <c>8</c> <c>{6, 14, 29, 47, 61, 52, 30, 14, 3}/256</c>
+ <c>9</c> <c>{1, 15, 23, 35, 51, 50, 40, 30, 10, 1}/256</c>
+<c>10</c> <c>{1, 1, 21, 32, 42, 52, 46, 41, 18, 1, 1}/256</c>
+<c>11</c> <c>{1, 6, 16, 27, 36, 42, 42, 36, 27, 16, 6, 1}/256</c>
+<c>12</c> <c>{1, 5, 12, 21, 31, 38, 40, 38, 31, 21, 12, 5, 1}/256</c>
+<c>13</c> <c>{1, 3, 9, 17, 26, 34, 38, 38, 34, 26, 17, 9, 3, 1}/256</c>
+<c>14</c> <c>{1, 3, 7, 14, 22, 29, 34, 36, 34, 29, 22, 14, 7, 3, 1}/256</c>
+<c>15</c> <c>{1, 2, 5, 11, 18, 25, 31, 35, 35, 31, 25, 18, 11, 5, 2, 1}/256</c>
+<c>16</c> <c>{1, 1, 4, 9, 15, 21, 28, 32, 34, 32, 28, 21, 15, 9, 4, 1, 1}/256</c>
+</texttable>
+
+<texttable anchor="silk_shell_code0_pdfs"
+ title="PDFs for Pulse Count Split, 2 Sample Partitions">
+<ttcol>Pulse Count</ttcol>
+<ttcol>PDF</ttcol>
+ <c>1</c> <c>{128, 128}/256</c>
+ <c>2</c> <c>{42, 172, 42}/256</c>
+ <c>3</c> <c>{21, 107, 107, 21}/256</c>
+ <c>4</c> <c>{12, 60, 112, 61, 11}/256</c>
+ <c>5</c> <c>{8, 34, 86, 86, 35, 7}/256</c>
+ <c>6</c> <c>{8, 23, 55, 90, 55, 20, 5}/256</c>
+ <c>7</c> <c>{5, 15, 38, 72, 72, 36, 15, 3}/256</c>
+ <c>8</c> <c>{6, 12, 27, 52, 77, 47, 20, 10, 5}/256</c>
+ <c>9</c> <c>{6, 19, 28, 35, 40, 40, 35, 28, 19, 6}/256</c>
+<c>10</c> <c>{4, 14, 22, 31, 37, 40, 37, 31, 22, 14, 4}/256</c>
+<c>11</c> <c>{3, 10, 18, 26, 33, 38, 38, 33, 26, 18, 10, 3}/256</c>
+<c>12</c> <c>{2, 8, 13, 21, 29, 36, 38, 36, 29, 21, 13, 8, 2}/256</c>
+<c>13</c> <c>{1, 5, 10, 17, 25, 32, 38, 38, 32, 25, 17, 10, 5, 1}/256</c>
+<c>14</c> <c>{1, 4, 7, 13, 21, 29, 35, 36, 35, 29, 21, 13, 7, 4, 1}/256</c>
+<c>15</c> <c>{1, 2, 5, 10, 17, 25, 32, 36, 36, 32, 25, 17, 10, 5, 2, 1}/256</c>
+<c>16</c> <c>{1, 2, 4, 7, 13, 21, 28, 34, 36, 34, 28, 21, 13, 7, 4, 2, 1}/256</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_shell_lsb" title="LSB Decoding">
+<t>
+After the decoder reads the pulse locations for all blocks, it reads the LSBs
+ (if any) for each block in turn.
+Inside each block, it reads all the LSBs for each coefficient in turn, even
+ those where no pulses were allocated, before proceeding to the next one.
+For 10&nbsp;ms MB frames, it reads LSBs even for the extra 8&nbsp;samples in
+ the last block.
+The LSBs are coded from most significant to least significant, and they all use
+ the PDF in <xref target="silk_shell_lsb_pdf"/>.
+</t>
+
+<texttable anchor="silk_shell_lsb_pdf" title="PDF for Excitation LSBs">
+<ttcol>PDF</ttcol>
+<c>{136, 120}/256</c>
+</texttable>
+
+<t>
+The number of LSBs read for each coefficient in a block is determined in
+ <xref target="silk_pulse_counts"/>.
+The magnitude of the coefficient is initially equal to the number of pulses
+ placed at that location in <xref target="silk_pulse_locations"/>.
+As each LSB is decoded, the magnitude is doubled, and then the value of the LSB
+ added to it, to obtain an updated magnitude.
+</t>
+</section>
+
+<section anchor="silk_signs" title="Sign Decoding">
+<t>
+After decoding the pulse locations and the LSBs, the decoder knows the
+ magnitude of each coefficient in the excitation.
+It then decodes a sign for all coefficients with a non-zero magnitude, using
+ one of the PDFs from <xref target="silk_sign_pdfs"/>.
+If the value decoded is 0, then the coefficient magnitude is negated.
+Otherwise, it remains positive.
+</t>
+
+<t>
+The decoder chooses the PDF for the sign based on the signal type and
+ quantization offset type (from <xref target="silk_frame_type"/>) and the
+ number of pulses in the block (from <xref target="silk_pulse_counts"/>).
+The number of pulses in the block does not take into account any LSBs.
+Most PDFs are skewed towards negative signs because of the quantization offset,
+ but the PDFs for zero pulses are highly skewed towards positive signs.
+If a block contains many positive coefficients, it is sometimes beneficial to
+ code it solely using LSBs (i.e., with zero pulses), since the encoder may be
+ able to save enough bits on the signs to justify the less efficient
+ coefficient magnitude encoding.
+</t>
+
+<texttable anchor="silk_sign_pdfs"
+ title="PDFs for Excitation Signs">
+<ttcol>Signal Type</ttcol>
+<ttcol>Quantization Offset Type</ttcol>
+<ttcol>Pulse Count</ttcol>
+<ttcol>PDF</ttcol>
+<c>Inactive</c> <c>Low</c>  <c>0</c>         <c>{2, 254}/256</c>
+<c>Inactive</c> <c>Low</c>  <c>1</c>         <c>{207, 49}/256</c>
+<c>Inactive</c> <c>Low</c>  <c>2</c>         <c>{189, 67}/256</c>
+<c>Inactive</c> <c>Low</c>  <c>3</c>         <c>{179, 77}/256</c>
+<c>Inactive</c> <c>Low</c>  <c>4</c>         <c>{174, 82}/256</c>
+<c>Inactive</c> <c>Low</c>  <c>5</c>         <c>{163, 93}/256</c>
+<c>Inactive</c> <c>Low</c>  <c>6 or more</c> <c>{157, 99}/256</c>
+<c>Inactive</c> <c>High</c> <c>0</c>         <c>{58, 198}/256</c>
+<c>Inactive</c> <c>High</c> <c>1</c>         <c>{245, 11}/256</c>
+<c>Inactive</c> <c>High</c> <c>2</c>         <c>{238, 18}/256</c>
+<c>Inactive</c> <c>High</c> <c>3</c>         <c>{232, 24}/256</c>
+<c>Inactive</c> <c>High</c> <c>4</c>         <c>{225, 31}/256</c>
+<c>Inactive</c> <c>High</c> <c>5</c>         <c>{220, 36}/256</c>
+<c>Inactive</c> <c>High</c> <c>6 or more</c> <c>{211, 45}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>0</c>         <c>{1, 255}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>1</c>         <c>{210, 46}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>2</c>         <c>{190, 66}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>3</c>         <c>{178, 78}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>4</c>         <c>{169, 87}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>5</c>         <c>{162, 94}/256</c>
+<c>Unvoiced</c> <c>Low</c>  <c>6 or more</c> <c>{152, 104}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>0</c>         <c>{48, 208}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>1</c>         <c>{242, 14}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>2</c>         <c>{235, 21}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>3</c>         <c>{224, 32}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>4</c>         <c>{214, 42}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>5</c>         <c>{205, 51}/256</c>
+<c>Unvoiced</c> <c>High</c> <c>6 or more</c> <c>{190, 66}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>0</c>         <c>{1, 255}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>1</c>         <c>{162, 94}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>2</c>         <c>{152, 104}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>3</c>         <c>{147, 109}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>4</c>         <c>{144, 112}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>5</c>         <c>{141, 115}/256</c>
+<c>Voiced</c>   <c>Low</c>  <c>6 or more</c> <c>{138, 118}/256</c>
+<c>Voiced</c>   <c>High</c> <c>0</c>         <c>{8, 248}/256</c>
+<c>Voiced</c>   <c>High</c> <c>1</c>         <c>{203, 53}/256</c>
+<c>Voiced</c>   <c>High</c> <c>2</c>         <c>{187, 69}/256</c>
+<c>Voiced</c>   <c>High</c> <c>3</c>         <c>{176, 80}/256</c>
+<c>Voiced</c>   <c>High</c> <c>4</c>         <c>{168, 88}/256</c>
+<c>Voiced</c>   <c>High</c> <c>5</c>         <c>{161, 95}/256</c>
+<c>Voiced</c>   <c>High</c> <c>6 or more</c> <c>{154, 102}/256</c>
+</texttable>
+
+</section>
+
+<section anchor="silk_excitation_reconstruction"
+ title="Reconstructing the Excitation">
+
+<t>
+After the signs have been read, there is enough information to reconstruct the
+ complete excitation signal.
+This requires adding a constant quantization offset to each non-zero sample,
+ and then pseudorandomly inverting and offsetting every sample.
+The constant quantization offset varies depending on the signal type and
+ quantization offset type (see <xref target="silk_frame_type"/>).
+</t>
+
+<texttable anchor="silk_quantization_offsets"
+ title="Excitation Quantization Offsets">
+<ttcol align="left">Signal Type</ttcol>
+<ttcol align="left">Quantization Offset Type</ttcol>
+<ttcol align="right">Quantization Offset (Q23)</ttcol>
+<c>Inactive</c> <c>Low</c>  <c>25</c>
+<c>Inactive</c> <c>High</c> <c>60</c>
+<c>Unvoiced</c> <c>Low</c>  <c>25</c>
+<c>Unvoiced</c> <c>High</c> <c>60</c>
+<c>Voiced</c>   <c>Low</c>   <c>8</c>
+<c>Voiced</c>   <c>High</c> <c>25</c>
+</texttable>
+
+<t>
+Let e_raw[i] be the raw excitation value at position i, with a magnitude
+ composed of the pulses at that location (see
+ <xref target="silk_pulse_locations"/>) combined with any additional LSBs (see
+ <xref target="silk_shell_lsb"/>), and with the corresponding sign decoded in
+ <xref target="silk_signs"/>.
+Additionally, let seed be the current pseudorandom seed, which is initialized
+ to the value decoded from <xref target="silk_seed"/> for the first sample in
+ the current SILK frame, and updated for each subsequent sample according to
+ the procedure below.
+Finally, let offset_Q23 be the quantization offset from
+ <xref target="silk_quantization_offsets"/>.
+Then the following procedure produces the final reconstructed excitation value,
+ e_Q23[i]:
+<figure align="center">
+<artwork align="center"><![CDATA[
+e_Q23[i] = (e_raw[i] << 8) - sign(e_raw[i])*20 + offset_Q23;
+    seed = (196314165*seed + 907633515) & 0xFFFFFFFF;
+e_Q23[i] = (seed & 0x80000000) ? -e_Q23[i] : e_Q23[i];
+    seed = (seed + e_raw[i]) & 0xFFFFFFFF;
+]]></artwork>
+</figure>
+When e_raw[i] is zero, sign() returns 0 by the definition in
+ <xref target="sign"/>, so the factor of 20 does not get added.
+The final e_Q23[i] value may require more than 16 bits per sample, but will not
+ require more than 23, including the sign.
+</t>
+
+</section>
+
+</section>
+
+<section anchor="silk_frame_reconstruction" toc="include"
+ title="SILK Frame Reconstruction">
+
+<t>
+The remainder of the reconstruction process for the frame does not need to be
+ bit-exact, as small errors should only introduce proportionally small
+ distortions.
+Although the reference implementation only includes a fixed-point version of
+ the remaining steps, this section describes them in terms of a floating-point
+ version for simplicity.
+This produces a signal with a nominal range of -1.0 to 1.0.
+</t>
+
+<t>
+silk_decode_core() (decode_core.c) contains the code for the main
+ reconstruction process.
+It proceeds subframe-by-subframe, since quantization gains, LTP parameters, and
+ (in 20&nbsp;ms SILK frames) LPC coefficients can vary from one to the
+ next.
+</t>
+
+<t>
+Let a_Q12[k] be the LPC coefficients for the current subframe.
+If this is the first or second subframe of a 20&nbsp;ms SILK frame and the LSF
+ interpolation factor, w_Q2 (see <xref target="silk_nlsf_interpolation"/>), is
+ less than 4, then these correspond to the final LPC coefficients produced by
+ <xref target="silk_lpc_gain_limit"/> from the interpolated LSF coefficients,
+ n1_Q15[k] (computed in <xref target="silk_nlsf_interpolation"/>).
+Otherwise, they correspond to the final LPC coefficients produced from the
+ uninterpolated LSF coefficients for the current frame, n2_Q15[k].
+</t>
+
+<t>
+Also, let n be the number of samples in a subframe (40 for NB, 60 for MB, and
+ 80 for WB), s be the index of the current subframe in this SILK frame (0 or 1
+ for 10&nbsp;ms frames, or 0 to 3 for 20&nbsp;ms frames), and j be the index of
+ the first sample in the residual corresponding to the current subframe.
+</t>
+
+<section anchor="silk_ltp_synthesis" title="LTP Synthesis">
+<t>
+Voiced SILK frames (see <xref target="silk_frame_type"/>) pass the excitation
+ through an LTP filter using the parameters decoded in
+ <xref target="silk_ltp_params"/> to produce an LPC residual.
+The LTP filter requires LPC residual values from before the current subframe as
+ input.
+However, since the LPC coefficients may have changed, it obtains this residual
+ by "rewhitening" the corresponding output signal using the LPC coefficients
+ from the current subframe.
+Let out[i] for
+ (j&nbsp;-&nbsp;pitch_lags[s]&nbsp;-&nbsp;d_LPC&nbsp;-&nbsp;2)&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;j
+ be the fully reconstructed output signal from the last
+ (pitch_lags[s]&nbsp;+&nbsp;d_LPC&nbsp;+&nbsp;2) samples of previous subframes
+ (see <xref target="silk_lpc_synthesis"/>), where pitch_lags[s] is the pitch
+ lag for the current subframe from <xref target="silk_ltp_lags"/>.
+During reconstruction of the first subframe for this channel after either
+<list style="symbols">
+<t>An uncoded regular SILK frame (if this is the side channel), or</t>
+<t>A decoder reset (see <xref target="decoder-reset"/>),</t>
+</list>
+ out[] is rewhitened into an LPC residual,
+ res[i], via
+<figure align="center">
+<artwork align="center"><![CDATA[
+         4.0*LTP_scale_Q14
+res[i] = ----------------- * clamp(-1.0,
+            gain_Q16[s]
+
+                                   d_LPC-1
+                                     __              a_Q12[k]
+                            out[i] - \  out[i-k-1] * --------, 1.0) .
+                                     /_               4096.0
+                                     k=0
+]]></artwork>
+</figure>
+This requires storage to buffer up to 306 values of out[i] from previous
+ subframes.
+This corresponds to WB with a maximum pitch lag of
+ 18&nbsp;ms&nbsp;*&nbsp;16&nbsp;kHz samples, plus 16 samples for d_LPC, plus 2
+ samples for the width of the LTP filter.
+</t>
+
+<t>
+Let e_Q23[i] for j&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;(j&nbsp;+&nbsp;n) be the
+ excitation for the current subframe, and b_Q7[k] for
+ 0&nbsp;&lt;=&nbsp;k&nbsp;&lt;&nbsp;5 be the coefficients of the LTP filter
+ taken from the codebook entry in one of
+ Tables&nbsp;<xref format="counter" target="silk_ltp_filter_coeffs0"/>
+ through&nbsp;<xref format="counter" target="silk_ltp_filter_coeffs2"/>
+ corresponding to the index decoded for the current subframe in
+ <xref target="silk_ltp_filter"/>.
+Then for i such that j&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;(j&nbsp;+&nbsp;n),
+ the LPC residual is
+<figure align="center">
+<artwork align="center"><![CDATA[
+                      4
+          e_Q23[i]   __                                  b_Q7[k]
+res[i] = --------- + \  res[i - pitch_lags[s] + 2 - k] * ------- .
+          2.0**23    /_                                   128.0
+                     k=0
+]]></artwork>
+</figure>
+</t>
+
+<t>
+For unvoiced frames, the LPC residual for
+ j&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;(j&nbsp;+&nbsp;n) is simply a normalized
+ copy of the excitation signal, i.e.,
+<figure align="center">
+<artwork align="center"><![CDATA[
+          e_Q23[i]
+res[i] = ---------
+          2.0**23
+]]></artwork>
+</figure>
+</t>
+</section>
+
+<section anchor="silk_lpc_synthesis" title="LPC Synthesis">
+<t>
+LPC synthesis uses the short-term LPC filter to predict the next output
+ coefficient.
+For i such that (j&nbsp;-&nbsp;d_LPC)&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;j, let
+ lpc[i] be the result of LPC synthesis from the last d_LPC samples of the
+ previous subframe, or zeros in the first subframe for this channel after
+ either
+<list style="symbols">
+<t>An uncoded regular SILK frame (if this is the side channel), or</t>
+<t>A decoder reset (see <xref target="decoder-reset"/>).</t>
+</list>
+Then for i such that j&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;(j&nbsp;+&nbsp;n), the
+ result of LPC synthesis for the current subframe is
+<figure align="center">
+<artwork align="center"><![CDATA[
+                              d_LPC-1
+         gain_Q16[i]            __              a_Q12[k]
+lpc[i] = ----------- * res[i] + \  lpc[i-k-1] * -------- .
+           65536.0              /_               4096.0
+                                k=0
+]]></artwork>
+</figure>
+The decoder saves the final d_LPC values, i.e., lpc[i] such that
+ (j&nbsp;+&nbsp;n&nbsp;-&nbsp;d_LPC)&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;(j&nbsp;+&nbsp;n),
+ to feed into the LPC synthesis of the next subframe.
+This requires storage for up to 16 values of lpc[i] (for WB frames).
+</t>
+
+<t>
+Then, the signal is clamped into the final nominal range:
+<figure align="center">
+<artwork align="center"><![CDATA[
+out[i] = clamp(-1.0, lpc[i], 1.0) .
+]]></artwork>
+</figure>
+This clamping occurs entirely after the LPC synthesis filter has run.
+The decoder saves the unclamped values, lpc[i], to feed into the LPC filter for
+ the next subframe, but saves the clamped values, out[i], for rewhitening in
+ voiced frames.
+</t>
+</section>
+
+</section>
+
+</section>
+
+<section anchor="silk_stereo_unmixing" title="Stereo Unmixing">
+<t>
+For stereo streams, after decoding a frame from each channel, the decoder must
+ convert the mid-side (MS) representation into a left-right (LR)
+ representation.
+The function silk_stereo_MS_to_LR (stereo_MS_to_LR.c) implements this process.
+In it, the decoder predicts the side channel using a) a simple low-passed
+ version of the mid channel, and b) the unfiltered mid channel, using the
+ prediction weights decoded in <xref target="silk_stereo_pred"/>.
+This simple low-pass filter imposes a one-sample delay, and the unfiltered
+mid channel is also delayed by one sample.
+In order to allow seamless switching between stereo and mono, mono streams must
+ also impose the same one-sample delay.
+The encoder requires an additional one-sample delay for both mono and stereo
+ streams, though an encoder may omit the delay for mono if it knows it will
+ never switch to stereo.
+</t>
+
+<t>
+The unmixing process operates in two phases.
+The first phase lasts for 8&nbsp;ms, during which it interpolates the
+ prediction weights from the previous frame, prev_w0_Q13 and prev_w1_Q13, to
+ the values for the current frame, w0_Q13 and w1_Q13.
+The second phase simply uses these weights for the remainder of the frame.
+</t>
+
+<t>
+Let mid[i] and side[i] be the contents of out[i] (from
+ <xref target="silk_lpc_synthesis"/>) for the current mid and side channels,
+ respectively, and let left[i] and right[i] be the corresponding stereo output
+ channels.
+If the side channel is not coded (see <xref target="silk_mid_only_flag"/>),
+ then side[i] is set to zero.
+Also let j be defined as in <xref target="silk_frame_reconstruction"/>, n1 be
+ the number of samples in phase&nbsp;1 (64 for NB, 96 for MB, and 128 for WB),
+ and n2 be the total number of samples in the frame.
+Then for i such that j&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;(j&nbsp;+&nbsp;n2),
+ the left and right channel output is
+<figure align="center">
+<artwork align="center"><![CDATA[
+              prev_w0_Q13                  (w0_Q13 - prev_w0_Q13)
+        w0 =  ----------- + min(i - j, n1)*---------------------- ,
+                8192.0                           8192.0*n1
+
+              prev_w1_Q13                  (w1_Q13 - prev_w1_Q13)
+        w1 =  ----------- + min(i - j, n1)*---------------------- ,
+                8192.0                            8192.0*n1
+
+             mid[i-2] + 2*mid[i-1] + mid[i]
+        p0 = ------------------------------ ,
+                          4.0
+
+ left[i] = clamp(-1.0, (1 + w1)*mid[i-1] + side[i-1] + w0*p0, 1.0) ,
+
+right[i] = clamp(-1.0, (1 - w1)*mid[i-1] - side[i-1] - w0*p0, 1.0) .
+]]></artwork>
+</figure>
+These formulas require two samples prior to index&nbsp;j, the start of the
+ frame, for the mid channel, and one prior sample for the side channel.
+For the first frame after a decoder reset, zeros are used instead.
+</t>
+
+</section>
+
+<section title="Resampling">
+<t>
+After stereo unmixing (if any), the decoder applies resampling to convert the
+ decoded SILK output to the sample rate desired by the application.
+This is necessary when decoding a Hybrid frame at SWB or FB sample rates, or
+ whenever the decoder wants the output at a different sample rate than the
+ internal SILK sampling rate (e.g., to allow a constant sample rate when the
+ audio bandwidth changes, or to allow mixing with audio from other
+ applications).
+The resampler itself is non-normative, and a decoder can use any method it
+ wants to perform the resampling.
+</t>
+
+<t>
+However, a minimum amount of delay is imposed to allow the resampler to
+ operate, and this delay is normative, so that the corresponding delay can be
+ applied to the MDCT layer in the encoder.
+A decoder is always free to use a resampler which requires more delay than
+ allowed for here (e.g., to improve quality), but it must then delay the output
+ of the MDCT layer by this extra amount.
+Keeping as much delay as possible on the encoder side allows an encoder which
+ knows it will never use any of the SILK or Hybrid modes to skip this delay.
+By contrast, if it were all applied by the decoder, then a decoder which
+ processes audio in fixed-size blocks would be forced to delay the output of
+ CELT frames just in case of a later switch to a SILK or Hybrid mode.
+</t>
+
+<t>
+<xref target="silk_resampler_delay_alloc"/> gives the maximum resampler delay
+ in samples at 48&nbsp;kHz for each SILK audio bandwidth.
+Because the actual output rate may not be 48&nbsp;kHz, it may not be possible
+ to achieve exactly these delays while using a whole number of input or output
+ samples.
+The reference implementation is able to resample to any of the supported
+ output sampling rates (8, 12, 16, 24, or 48&nbsp;kHz) within or near this
+ delay constraint.
+Some resampling filters (including those used by the reference implementation)
+ may add a delay that is not an exact integer, or is not linear-phase, and so
+ cannot be represented by a single delay at all frequencies.
+However, such deviations are unlikely to be perceptible, and the comparison
+ tool described in <xref target="conformance"/> is designed to be relatively
+ insensitive to them.
+The delays listed here are the ones that should be targeted by the encoder.
+</t>
+
+<texttable anchor="silk_resampler_delay_alloc"
+ title="SILK Resampler Delay Allocations">
+<ttcol>Audio Bandwidth</ttcol>
+<ttcol>Delay in millisecond</ttcol>
+<c>NB</c> <c>0.538</c>
+<c>MB</c> <c>0.692</c>
+<c>WB</c> <c>0.706</c>
+</texttable>
+
+<t>
+NB is given a smaller decoder delay allocation than MB and WB to allow a
+ higher-order filter when resampling to 8&nbsp;kHz in both the encoder and
+ decoder.
+This implies that the audio content of two SILK frames operating at different
+ bandwidths are not perfectly aligned in time.
+This is not an issue for any transitions described in
+ <xref target="switching"/>, because they all involve a SILK decoder reset.
+When the decoder is reset, any samples remaining in the resampling buffer
+ are discarded, and the resampler is re-initialized with silence.
+</t>
+
+</section>
+
+</section>
+
+
+<section title="CELT Decoder">
+
+<t>
+The CELT layer of Opus is based on the Modified Discrete Cosine Transform
+<xref target='MDCT'/> with partially overlapping windows of 5 to 22.5 ms.
+The main principle behind CELT is that the MDCT spectrum is divided into
+bands that (roughly) follow the Bark scale, i.e., the scale of the ear's
+critical bands&nbsp;<xref target="Zwicker61"/>. The normal CELT layer uses 21 of those bands, though Opus
+ Custom (see <xref target="opus-custom"/>) may use a different number of bands.
+In Hybrid mode, the first 17 bands (up to 8&nbsp;kHz) are not coded.
+A band can contain as little as one MDCT bin per channel, and as many as 176
+bins per channel, as detailed in <xref target="celt_band_sizes"/>.
+In each band, the gain (energy) is coded separately from
+the shape of the spectrum. Coding the gain explicitly makes it easy to
+preserve the spectral envelope of the signal. The remaining unit-norm shape
+vector is encoded using a Pyramid Vector Quantizer (PVQ)&nbsp;<xref target='PVQ-decoder'/>.
+</t>
+
+<texttable anchor="celt_band_sizes"
+ title="MDCT Bins Per Channel Per Band for Each Frame Size">
+<ttcol>Frame Size:</ttcol>
+<ttcol align="right">2.5&nbsp;ms</ttcol>
+<ttcol align="right">5&nbsp;ms</ttcol>
+<ttcol align="right">10&nbsp;ms</ttcol>
+<ttcol align="right">20&nbsp;ms</ttcol>
+<ttcol align="right">Start Frequency</ttcol>
+<ttcol align="right">Stop Frequency</ttcol>
+<c>Band</c> <c>Bins:</c> <c/> <c/> <c/> <c/> <c/>
+ <c>0</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>     <c>0&nbsp;Hz</c>   <c>200&nbsp;Hz</c>
+ <c>1</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>   <c>200&nbsp;Hz</c>   <c>400&nbsp;Hz</c>
+ <c>2</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>   <c>400&nbsp;Hz</c>   <c>600&nbsp;Hz</c>
+ <c>3</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>   <c>600&nbsp;Hz</c>   <c>800&nbsp;Hz</c>
+ <c>4</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>   <c>800&nbsp;Hz</c>  <c>1000&nbsp;Hz</c>
+ <c>5</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>  <c>1000&nbsp;Hz</c>  <c>1200&nbsp;Hz</c>
+ <c>6</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>  <c>1200&nbsp;Hz</c>  <c>1400&nbsp;Hz</c>
+ <c>7</c>  <c>1</c>  <c>2</c>  <c>4</c>   <c>8</c>  <c>1400&nbsp;Hz</c>  <c>1600&nbsp;Hz</c>
+ <c>8</c>  <c>2</c>  <c>4</c>  <c>8</c>  <c>16</c>  <c>1600&nbsp;Hz</c>  <c>2000&nbsp;Hz</c>
+ <c>9</c>  <c>2</c>  <c>4</c>  <c>8</c>  <c>16</c>  <c>2000&nbsp;Hz</c>  <c>2400&nbsp;Hz</c>
+<c>10</c>  <c>2</c>  <c>4</c>  <c>8</c>  <c>16</c>  <c>2400&nbsp;Hz</c>  <c>2800&nbsp;Hz</c>
+<c>11</c>  <c>2</c>  <c>4</c>  <c>8</c>  <c>16</c>  <c>2800&nbsp;Hz</c>  <c>3200&nbsp;Hz</c>
+<c>12</c>  <c>4</c>  <c>8</c> <c>16</c>  <c>32</c>  <c>3200&nbsp;Hz</c>  <c>4000&nbsp;Hz</c>
+<c>13</c>  <c>4</c>  <c>8</c> <c>16</c>  <c>32</c>  <c>4000&nbsp;Hz</c>  <c>4800&nbsp;Hz</c>
+<c>14</c>  <c>4</c>  <c>8</c> <c>16</c>  <c>32</c>  <c>4800&nbsp;Hz</c>  <c>5600&nbsp;Hz</c>
+<c>15</c>  <c>6</c> <c>12</c> <c>24</c>  <c>48</c>  <c>5600&nbsp;Hz</c>  <c>6800&nbsp;Hz</c>
+<c>16</c>  <c>6</c> <c>12</c> <c>24</c>  <c>48</c>  <c>6800&nbsp;Hz</c>  <c>8000&nbsp;Hz</c>
+<c>17</c>  <c>8</c> <c>16</c> <c>32</c>  <c>64</c>  <c>8000&nbsp;Hz</c>  <c>9600&nbsp;Hz</c>
+<c>18</c> <c>12</c> <c>24</c> <c>48</c>  <c>96</c>  <c>9600&nbsp;Hz</c> <c>12000&nbsp;Hz</c>
+<c>19</c> <c>18</c> <c>36</c> <c>72</c> <c>144</c> <c>12000&nbsp;Hz</c> <c>15600&nbsp;Hz</c>
+<c>20</c> <c>22</c> <c>44</c> <c>88</c> <c>176</c> <c>15600&nbsp;Hz</c> <c>20000&nbsp;Hz</c>
+</texttable>
+
+<t>
+Transients are notoriously difficult for transform codecs to code.
+CELT uses two different strategies for them:
+<list style="numbers">
+<t>Using multiple smaller MDCTs instead of a single large MDCT, and</t>
+<t>Dynamic time-frequency resolution changes (See <xref target='tf-change'/>).</t>
+</list>
+To improve quality on highly tonal and periodic signals, CELT includes
+a prefilter/postfilter combination. The prefilter on the encoder side
+attenuates the signal's harmonics. The postfilter on the decoder side
+restores the original gain of the harmonics, while shaping the coding noise
+to roughly follow the harmonics. Such noise shaping reduces the perception
+of the noise.
+</t>
+
+<t>
+When coding a stereo signal, three coding methods are available:
+<list style="symbols">
+<t>mid-side stereo: encodes the mean and the difference of the left and right channels,</t>
+<t>intensity stereo: only encodes the mean of the left and right channels (discards the difference),</t>
+<t>dual stereo: encodes the left and right channels separately.</t>
+</list>
+</t>
+
+<t>
+An overview of the decoder is given in <xref target="celt-decoder-overview"/>.
+</t>
+
+<figure anchor="celt-decoder-overview" title="Structure of the CELT decoder">
+<artwork align="center"><![CDATA[
+               +---------+
+               | Coarse  |
+            +->| decoder |----+
+            |  +---------+    |
+            |                 |
+            |  +---------+    v
+            |  |  Fine   |  +---+
+            +->| decoder |->| + |
+            |  +---------+  +---+
+            |       ^         |
++---------+ |       |         |
+|  Range  | | +----------+    v
+| Decoder |-+ |   Bit    | +------+
++---------+ | |Allocation| | 2**x |
+            | +----------+ +------+
+            |       |         |
+            |       v         v               +--------+
+            |  +---------+  +---+  +-------+  | pitch  |
+            +->|   PVQ   |->| * |->| IMDCT |->| post-  |--->
+            |  | decoder |  +---+  +-------+  | filter |
+            |  +---------+                    +--------+
+            |                                      ^
+            +--------------------------------------+
+]]></artwork>
+</figure>
+
+<t>
+The decoder is based on the following symbols and sets of symbols:
+</t>
+
+<texttable anchor="celt_symbols"
+ title="Order of the Symbols in the CELT Section of the Bitstream">
+<ttcol align="center">Symbol(s)</ttcol>
+<ttcol align="center">PDF</ttcol>
+<ttcol align="center">Condition</ttcol>
+<c>silence</c>      <c>{32767, 1}/32768</c> <c></c>
+<c>post-filter</c>  <c>{1, 1}/2</c> <c></c>
+<c>octave</c>       <c>uniform (6)</c><c>post-filter</c>
+<c>period</c>       <c>raw bits (4+octave)</c><c>post-filter</c>
+<c>gain</c>         <c>raw bits (3)</c><c>post-filter</c>
+<c>tapset</c>       <c>{2, 1, 1}/4</c><c>post-filter</c>
+<c>transient</c>    <c>{7, 1}/8</c><c></c>
+<c>intra</c>        <c>{7, 1}/8</c><c></c>
+<c>coarse energy</c><c><xref target="energy-decoding"/></c><c></c>
+<c>tf_change</c>    <c><xref target="transient-decoding"/></c><c></c>
+<c>tf_select</c>    <c>{1, 1}/2</c><c><xref target="transient-decoding"/></c>
+<c>spread</c>       <c>{7, 2, 21, 2}/32</c><c></c>
+<c>dyn. alloc.</c>  <c><xref target="allocation"/></c><c></c>
+<c>alloc. trim</c>  <c>{2, 2, 5, 10, 22, 46, 22, 10, 5, 2, 2}/128</c><c></c>
+<c>skip</c>         <c>{1, 1}/2</c><c><xref target="allocation"/></c>
+<c>intensity</c>    <c>uniform</c><c><xref target="allocation"/></c>
+<c>dual</c>         <c>{1, 1}/2</c><c></c>
+<c>fine energy</c>  <c><xref target="energy-decoding"/></c><c></c>
+<c>residual</c>     <c><xref target="PVQ-decoder"/></c><c></c>
+<c>anti-collapse</c><c>{1, 1}/2</c><c><xref target="anti-collapse"/></c>
+<c>finalize</c>     <c><xref target="energy-decoding"/></c><c></c>
+</texttable>
+
+<t>
+The decoder extracts information from the range-coded bitstream in the order
+described in <xref target='celt_symbols'/>. In some circumstances, it is
+possible for a decoded value to be out of range due to a very small amount of redundancy
+in the encoding of large integers by the range coder.
+In that case, the decoder should assume there has been an error in the coding,
+decoding, or transmission and SHOULD take measures to conceal the error and/or report
+to the application that a problem has occurred. Such out of range errors cannot occur
+in the SILK layer.
+</t>
+
+<section anchor="transient-decoding" title="Transient Decoding">
+<t>
+The "transient" flag indicates whether the frame uses a single long MDCT or several short MDCTs.
+When it is set, then the MDCT coefficients represent multiple
+short MDCTs in the frame. When not set, the coefficients represent a single
+long MDCT for the frame. The flag is encoded in the bitstream with a probability of 1/8.
+In addition to the global transient flag is a per-band
+binary flag to change the time-frequency (tf) resolution independently in each band. The
+change in tf resolution is defined in tf_select_table[][] in celt.c and depends
+on the frame size, whether the transient flag is set, and the value of tf_select.
+The tf_select flag uses a 1/2 probability, but is only decoded
+if it can have an impact on the result knowing the value of all per-band
+tf_change flags.
+</t>
+</section>
+
+<section anchor="energy-decoding" title="Energy Envelope Decoding">
+
+<t>
+It is important to quantize the energy with sufficient resolution because
+any energy quantization error cannot be compensated for at a later
+stage. Regardless of the resolution used for encoding the spectral shape of a band,
+it is perceptually important to preserve the energy in each band. CELT uses a
+three-step coarse-fine-fine strategy for encoding the energy in the base-2 log
+domain, as implemented in quant_bands.c</t>
+
+<section anchor="coarse-energy-decoding" title="Coarse energy decoding">
+<t>
+Coarse quantization of the energy uses a fixed resolution of 6 dB
+(integer part of base-2 log). To minimize the bitrate, prediction is applied
+both in time (using the previous frame) and in frequency (using the previous
+bands). The part of the prediction that is based on the
+previous frame can be disabled, creating an "intra" frame where the energy
+is coded without reference to prior frames. The decoder first reads the intra flag
+to determine what prediction is used.
+The 2-D z-transform <xref target='z-transform'/> of
+the prediction filter is:
+<figure align="center">
+<artwork align="center"><![CDATA[
+                            -1          -1
+              (1 - alpha*z_l  )*(1 - z_b  )
+A(z_l, z_b) = -----------------------------
+                                 -1
+                     1 - beta*z_b
+]]></artwork>
+</figure>
+where b is the band index and l is the frame index. The prediction coefficients
+applied depend on the frame size in use when not using intra energy and are alpha=0, beta=4915/32768
+when using intra energy.
+The time-domain prediction is based on the final fine quantization of the previous
+frame, while the frequency domain (within the current frame) prediction is based
+on coarse quantization only (because the fine quantization has not been computed
+yet). The prediction is clamped internally so that fixed point implementations with
+limited dynamic range always remain in the same state as floating point implementations.
+We approximate the ideal
+probability distribution of the prediction error using a Laplace distribution
+with separate parameters for each frame size in intra- and inter-frame modes. These
+parameters are held in the e_prob_model table in quant_bands.c.
+The
+coarse energy quantization is performed by unquant_coarse_energy() and
+unquant_coarse_energy_impl() (quant_bands.c). The encoding of the Laplace-distributed values is
+implemented in ec_laplace_decode() (laplace.c).
+</t>
+
+</section>
+
+<section anchor="fine-energy-decoding" title="Fine energy quantization">
+<t>
+The number of bits assigned to fine energy quantization in each band is determined
+by the bit allocation computation described in <xref target="allocation"></xref>.
+Let B_i be the number of fine energy bits
+for band i; the refinement is an integer f in the range [0,2**B_i-1]. The mapping between f
+and the correction applied to the coarse energy is equal to (f+1/2)/2**B_i - 1/2. Fine
+energy quantization is implemented in quant_fine_energy() (quant_bands.c).
+</t>
+<t>
+When some bits are left "unused" after all other flags have been decoded, these bits
+are assigned to a "final" step of fine allocation. In effect, these bits are used
+to add one extra fine energy bit per band per channel. The allocation process
+determines two "priorities" for the final fine bits.
+Any remaining bits are first assigned only to bands of priority 0, starting
+from band 0 and going up. If all bands of priority 0 have received one bit per
+channel, then bands of priority 1 are assigned an extra bit per channel,
+starting from band 0. If any bits are left after this, they are left unused.
+This is implemented in unquant_energy_finalise() (quant_bands.c).
+</t>
+
+</section> <!-- fine energy -->
+
+</section> <!-- Energy decode -->
+
+<section anchor="allocation" title="Bit Allocation">
+
+<t>Because the bit allocation drives the decoding of the range-coder
+stream, it MUST be recovered exactly so that identical coding decisions are
+made in the encoder and decoder. Any deviation from the reference's resulting
+bit allocation will result in corrupted output, though implementers are
+free to implement the procedure in any way which produces identical results.</t>
+
+<t>The per-band gain-shape structure of the CELT layer ensures that using
+ the same number of bits for the spectral shape of a band in every frame will
+ result in a roughly constant signal-to-noise ratio in that band.
+This results in coding noise that has the same spectral envelope as the signal.
+The masking curve produced by a standard psychoacoustic model also closely
+ follows the spectral envelope of the signal.
+This structure means that the ideal allocation is more consistent from frame to
+ frame than it is for other codecs without an equivalent structure, and that a
+ fixed allocation provides fairly consistent perceptual
+ performance&nbsp;<xref target='Valin2010'/>.</t>
+
+<t>Many codecs transmit significant amounts of side information to control the
+ bit allocation within a frame.
+Often this control is only indirect, and must be exercised carefully to
+ achieve the desired rate constraints.
+The CELT layer, however, can adapt over a very wide range of rates, and thus
+ has a large number of codebook sizes to choose from for each band.
+Explicitly signaling the size of each of these codebooks would impose
+ considerable overhead, even though the allocation is relatively static from
+ frame to frame.
+This is because all of the information required to compute these codebook sizes
+ must be derived from a single frame by itself, in order to retain robustness
+ to packet loss, so the signaling cannot take advantage of knowledge of the
+ allocation in neighboring frames.
+This problem is exacerbated in low-latency (small frame size) applications,
+ which would include this overhead in every frame.</t>
+
+<t>For this reason, in the MDCT mode Opus uses a primarily implicit bit
+allocation. The available bitstream capacity is known in advance to both
+the encoder and decoder without additional signaling, ultimately from the
+packet sizes expressed by a higher-level protocol. Using this information,
+the codec interpolates an allocation from a hard-coded table.</t>
+
+<t>While the band-energy structure effectively models intra-band masking,
+it ignores the weaker inter-band masking, band-temporal masking, and
+other less significant perceptual effects. While these effects can
+often be ignored, they can become significant for particular samples. One
+mechanism available to encoders would be to simply increase the overall
+rate for these frames, but this is not possible in a constant rate mode
+and can be fairly inefficient. As a result three explicitly signaled
+mechanisms are provided to alter the implicit allocation:</t>
+
+<t>
+<list style="symbols">
+<t>Band boost</t>
+<t>Allocation trim</t>
+<t>Band skipping</t>
+</list>
+</t>
+
+<t>The first of these mechanisms, band boost, allows an encoder to boost
+the allocation in specific bands. The second, allocation trim, works by
+biasing the overall allocation towards higher or lower frequency bands. The third, band
+skipping, selects which low-precision high frequency bands
+will be allocated no shape bits at all.</t>
+
+<t>In stereo mode there are two additional parameters
+potentially coded as part of the allocation procedure: a parameter to allow the
+selective elimination of allocation for the 'side' (i.e., intensity stereo) in jointly coded bands,
+and a flag to deactivate joint coding (i.e., dual stereo). These values are not signaled if
+they would be meaningless in the overall context of the allocation.</t>
+
+<t>Because every signaled adjustment increases overhead and implementation
+complexity, none were included speculatively: the reference encoder makes use
+of all of these mechanisms. While the decision logic in the reference was
+found to be effective enough to justify the overhead and complexity, further
+analysis techniques may be discovered which increase the effectiveness of these
+parameters. As with other signaled parameters, an encoder is free to choose the
+values in any manner, but unless a technique is known to deliver superior
+perceptual results the methods used by the reference implementation should be
+used.</t>
+
+<t>The allocation process consists of the following steps: determining the per-band
+maximum allocation vector, decoding the boosts, decoding the tilt, determining
+the remaining capacity of the frame, searching the mode table for the
+entry nearest but not exceeding the available space (subject to the tilt, boosts, band
+maximums, and band minimums), linear interpolation, reallocation of
+unused bits with concurrent skip decoding, determination of the
+fine-energy vs. shape split, and final reallocation. This process results
+in a per-band shape allocation (in 1/8th bit units), a per-band fine-energy
+allocation (in 1 bit per channel units), a set of band priorities for
+controlling the use of remaining bits at the end of the frame, and a
+remaining balance of unallocated space, which is usually zero except
+at very high rates.</t>
+
+<t>
+The "static" bit allocation (in 1/8 bits) for a quality q, excluding the minimums, maximums,
+tilt and boosts, is equal to channels*N*alloc[band][q]&lt;&lt;LM&gt;&gt;2, where
+alloc[][] is given in <xref target="static_alloc"/> and LM=log2(frame_size/120). The allocation
+is obtained by linearly interpolating between two values of q (in steps of 1/64) to find the
+highest allocation that does not exceed the number of bits remaining.
+</t>
+
+<texttable anchor="static_alloc"
+ title="CELT Static Allocation Table">
+ <preamble>Rows indicate the MDCT bands, columns are the different quality (q) parameters. The units are 1/32 bit per MDCT bin.</preamble>
+<ttcol align="right">0</ttcol>
+<ttcol align="right">1</ttcol>
+<ttcol align="right">2</ttcol>
+<ttcol align="right">3</ttcol>
+<ttcol align="right">4</ttcol>
+<ttcol align="right">5</ttcol>
+<ttcol align="right">6</ttcol>
+<ttcol align="right">7</ttcol>
+<ttcol align="right">8</ttcol>
+<ttcol align="right">9</ttcol>
+<ttcol align="right">10</ttcol>
+<c>0</c><c>90</c><c>110</c><c>118</c><c>126</c><c>134</c><c>144</c><c>152</c><c>162</c><c>172</c><c>200</c>
+<c>0</c><c>80</c><c>100</c><c>110</c><c>119</c><c>127</c><c>137</c><c>145</c><c>155</c><c>165</c><c>200</c>
+<c>0</c><c>75</c><c>90</c><c>103</c><c>112</c><c>120</c><c>130</c><c>138</c><c>148</c><c>158</c><c>200</c>
+<c>0</c><c>69</c><c>84</c><c>93</c><c>104</c><c>114</c><c>124</c><c>132</c><c>142</c><c>152</c><c>200</c>
+<c>0</c><c>63</c><c>78</c><c>86</c><c>95</c><c>103</c><c>113</c><c>123</c><c>133</c><c>143</c><c>200</c>
+<c>0</c><c>56</c><c>71</c><c>80</c><c>89</c><c>97</c><c>107</c><c>117</c><c>127</c><c>137</c><c>200</c>
+<c>0</c><c>49</c><c>65</c><c>75</c><c>83</c><c>91</c><c>101</c><c>111</c><c>121</c><c>131</c><c>200</c>
+<c>0</c><c>40</c><c>58</c><c>70</c><c>78</c><c>85</c><c>95</c><c>105</c><c>115</c><c>125</c><c>200</c>
+<c>0</c><c>34</c><c>51</c><c>65</c><c>72</c><c>78</c><c>88</c><c>98</c><c>108</c><c>118</c><c>198</c>
+<c>0</c><c>29</c><c>45</c><c>59</c><c>66</c><c>72</c><c>82</c><c>92</c><c>102</c><c>112</c><c>193</c>
+<c>0</c><c>20</c><c>39</c><c>53</c><c>60</c><c>66</c><c>76</c><c>86</c><c>96</c><c>106</c><c>188</c>
+<c>0</c><c>18</c><c>32</c><c>47</c><c>54</c><c>60</c><c>70</c><c>80</c><c>90</c><c>100</c><c>183</c>
+<c>0</c><c>10</c><c>26</c><c>40</c><c>47</c><c>54</c><c>64</c><c>74</c><c>84</c><c>94</c><c>178</c>
+<c>0</c><c>0</c><c>20</c><c>31</c><c>39</c><c>47</c><c>57</c><c>67</c><c>77</c><c>87</c><c>173</c>
+<c>0</c><c>0</c><c>12</c><c>23</c><c>32</c><c>41</c><c>51</c><c>61</c><c>71</c><c>81</c><c>168</c>
+<c>0</c><c>0</c><c>0</c><c>15</c><c>25</c><c>35</c><c>45</c><c>55</c><c>65</c><c>75</c><c>163</c>
+<c>0</c><c>0</c><c>0</c><c>4</c><c>17</c><c>29</c><c>39</c><c>49</c><c>59</c><c>69</c><c>158</c>
+<c>0</c><c>0</c><c>0</c><c>0</c><c>12</c><c>23</c><c>33</c><c>43</c><c>53</c><c>63</c><c>153</c>
+<c>0</c><c>0</c><c>0</c><c>0</c><c>1</c><c>16</c><c>26</c><c>36</c><c>46</c><c>56</c><c>148</c>
+<c>0</c><c>0</c><c>0</c><c>0</c><c>0</c><c>10</c><c>15</c><c>20</c><c>30</c><c>45</c><c>129</c>
+<c>0</c><c>0</c><c>0</c><c>0</c><c>0</c><c>1</c><c>1</c><c>1</c><c>1</c><c>20</c><c>104</c>
+</texttable>
+
+<t>The maximum allocation vector is an approximation of the maximum space
+that can be used by each band for a given mode. The value is
+approximate because the shape encoding is variable rate (due
+to entropy coding of splitting parameters). Setting the maximum too low reduces the
+maximum achievable quality in a band while setting it too high
+may result in waste: bitstream capacity available at the end
+of the frame which can not be put to any use. The maximums
+specified by the codec reflect the average maximum. In the reference
+implementation, the maximums in bits/sample are precomputed in a static table
+(see cache_caps50[] in static_modes_float.h) for each band,
+for each value of LM, and for both mono and stereo.
+
+Implementations are expected
+to simply use the same table data, but the procedure for generating
+this table is included in rate.c as part of compute_pulse_cache().</t>
+
+<t>To convert the values in cache.caps into the actual maximums: first
+set nbBands to the maximum number of bands for this mode, and stereo to
+zero if stereo is not in use and one otherwise. For each band set N
+to the number of MDCT bins covered by the band (for one channel), set LM
+to the shift value for the frame size,
+then set i to nbBands*(2*LM+stereo). Then set the maximum for the band to
+the i-th index of cache.caps + 64 and multiply by the number of channels
+in the current frame (one or two) and by N, then divide the result by 4
+using integer division. The resulting vector will be called
+cap[]. The elements fit in signed 16-bit integers but do not fit in 8 bits.
+This procedure is implemented in the reference in the function init_caps() in celt.c.
+</t>
+
+<t>The band boosts are represented by a series of binary symbols which
+are entropy coded with very low probability. Each band can potentially be boosted
+multiple times, subject to the frame actually having enough room to obey
+the boost and having enough room to code the boost symbol. The default
+coding cost for a boost starts out at six bits (probability p=1/64), but subsequent boosts
+in a band cost only a single bit and every time a band is boosted the
+initial cost is reduced (down to a minimum of two bits, or p=1/4). Since the initial
+cost of coding a boost is 6 bits, the coding cost of the boost symbols when
+completely unused is 0.48 bits/frame for a 21 band mode (21*-log2(1-1/2**6)).</t>
+
+<t>To decode the band boosts: First set 'dynalloc_logp' to 6, the initial
+amount of storage required to signal a boost in bits, 'total_bits' to the
+size of the frame in 8th bits, 'total_boost' to zero, and 'tell' to the total number
+of 8th bits decoded
+so far. For each band from the coding start (0 normally, but 17 in Hybrid mode)
+to the coding end (which changes depending on the signaled bandwidth), the boost quanta
+in units of 1/8 bit is calculated as quanta = min(8*N, max(48, N)).
+This represents a boost step size of six bits, subject to a lower limit of
+1/8th&nbsp;bit/sample and an upper limit of 1&nbsp;bit/sample.
+Set 'boost' to zero and 'dynalloc_loop_logp'
+to dynalloc_logp. While dynalloc_loop_log (the current worst case symbol cost) in
+8th bits plus tell is less than total_bits plus total_boost and boost is less than cap[] for this
+band: Decode a bit from the bitstream with a with dynalloc_loop_logp as the cost
+of a one, update tell to reflect the current used capacity, if the decoded value
+is zero break the  loop otherwise add quanta to boost and total_boost, subtract quanta from
+total_bits, and set dynalloc_loop_log to 1. When the while loop finishes
+boost contains the boost for this band. If boost is non-zero and dynalloc_logp
+is greater than 2, decrease dynalloc_logp.  Once this process has been
+executed on all bands, the band boosts have been decoded. This procedure
+is implemented around line 2474 of celt.c.</t>
+
+<t>At very low rates it is possible that there won't be enough available
+space to execute the inner loop even once. In these cases band boost
+is not possible but its overhead is completely eliminated. Because of the
+high cost of band boost when activated, a reasonable encoder should not be
+using it at very low rates. The reference implements its dynalloc decision
+logic around line 1304 of celt.c.</t>
+
+<t>The allocation trim is a integer value from 0-10. The default value of
+5 indicates no trim. The trim parameter is entropy coded in order to
+lower the coding cost of less extreme adjustments. Values lower than
+5 bias the allocation towards lower frequencies and values above 5
+bias it towards higher frequencies. Like other signaled parameters, signaling
+of the trim is gated so that it is not included if there is insufficient space
+available in the bitstream. To decode the trim, first set
+the trim value to 5, then if and only if the count of decoded 8th bits so far (ec_tell_frac)
+plus 48 (6 bits) is less than or equal to the total frame size in 8th
+bits minus total_boost (a product of the above band boost procedure),
+decode the trim value using the PDF in <xref target="celt_trim_pdf"/>.</t>
+
+<texttable anchor="celt_trim_pdf" title="PDF for the Trim">
+<ttcol>PDF</ttcol>
+<c>{1, 1, 2, 5, 10, 22, 46, 22, 10, 5, 2, 2}/128</c>
+</texttable>
+
+<t>For 10 ms and 20 ms frames using short blocks and that have at least LM+2 bits left prior to
+the allocation process, then one anti-collapse bit is reserved in the allocation process so it can
+be decoded later. Following the the anti-collapse reservation, one bit is reserved for skip if available.</t>
+
+<t>For stereo frames, bits are reserved for intensity stereo and for dual stereo. Intensity stereo
+requires ilog2(end-start) bits. Those bits are reserved if there is enough bits left. Following this, one
+bit is reserved for dual stereo if available.</t>
+
+
+<t>The allocation computation begins by setting up some initial conditions.
+'total' is set to the remaining available 8th bits, computed by taking the
+size of the coded frame times 8 and subtracting ec_tell_frac(). From this value, one (8th bit)
+is subtracted to ensure that the resulting allocation will be conservative. 'anti_collapse_rsv'
+is set to 8 (8th bits) if and only if the frame is a transient, LM is greater than 1, and total is
+greater than or equal to (LM+2) * 8. Total is then decremented by anti_collapse_rsv and clamped
+to be equal to or greater than zero. 'skip_rsv' is set to 8 (8th bits) if total is greater than
+8, otherwise it is zero. Total is then decremented by skip_rsv. This reserves space for the
+final skipping flag.</t>
+
+<t>If the current frame is stereo, intensity_rsv is set to the conservative log2 in 8th bits
+of the number of coded bands for this frame (given by the table LOG2_FRAC_TABLE in rate.c). If
+intensity_rsv is greater than total then intensity_rsv is set to zero. Otherwise total is
+decremented by intensity_rsv, and if total is still greater than 8, dual_stereo_rsv is
+set to 8 and total is decremented by dual_stereo_rsv.</t>
+
+<t>The allocation process then computes a vector representing the hard minimum amounts allocation
+any band will receive for shape. This minimum is higher than the technical limit of the PVQ
+process, but very low rate allocations produce an excessively sparse spectrum and these bands
+are better served by having no allocation at all. For each coded band, set thresh[band] to
+twenty-four times the number of MDCT bins in the band and divide by 16. If 8 times the number
+of channels is greater, use that instead. This sets the minimum allocation to one bit per channel
+or 48 128th bits per MDCT bin, whichever is greater. The band-size dependent part of this
+value is not scaled by the channel count, because at the very low rates where this limit is
+applicable there will usually be no bits allocated to the side.</t>
+
+<t>The previously decoded allocation trim is used to derive a vector of per-band adjustments,
+'trim_offsets[]'. For each coded band take the alloc_trim and subtract 5 and LM. Then multiply
+the result by the number of channels, the number of MDCT bins in the shortest frame size for this mode,
+the number of remaining bands, 2**LM, and 8. Then divide this value by 64. Finally, if the
+number of MDCT bins in the band per channel is only one, 8 times the number of channels is subtracted
+in order to diminish the allocation by one bit, because width 1 bands receive greater benefit
+from the coarse energy coding.</t>
+
+
+</section>
+
+<section anchor="PVQ-decoder" title="Shape Decoding">
+<t>
+In each band, the normalized "shape" is encoded
+using a vector quantization scheme called a "pyramid vector quantizer".
+</t>
+
+<t>In
+the simplest case, the number of bits allocated in
+<xref target="allocation"></xref> is converted to a number of pulses as described
+by <xref target="bits-pulses"></xref>. Knowing the number of pulses and the
+number of samples in the band, the decoder calculates the size of the codebook
+as detailed in <xref target="cwrs-decoder"></xref>. The size is used to decode
+an unsigned integer (uniform probability model), which is the codeword index.
+This index is converted into the corresponding vector as explained in
+<xref target="cwrs-decoder"></xref>. This vector is then scaled to unit norm.
+</t>
+
+<section anchor="bits-pulses" title="Bits to Pulses">
+<t>
+Although the allocation is performed in 1/8th bit units, the quantization requires
+an integer number of pulses K. To do this, the encoder searches for the value
+of K that produces the number of bits nearest to the allocated value
+(rounding down if exactly halfway between two values), not to exceed
+the total number of bits available. For efficiency reasons, the search is performed against a
+precomputed allocation table which only permits some K values for each N. The number of
+codebook entries can be computed as explained in <xref target="cwrs-decoder"></xref>. The difference
+between the number of bits allocated and the number of bits used is accumulated to a
+"balance" (initialized to zero) that helps adjust the
+allocation for the next bands. One third of the balance is applied to the
+bit allocation of each band to help achieve the target allocation. The only
+exceptions are the band before the last and the last band, for which half the balance
+and the whole balance are applied, respectively.
+</t>
+</section>
+
+<section anchor="cwrs-decoder" title="PVQ Decoding">
+
+<t>
+Decoding of PVQ vectors is implemented in decode_pulses() (cwrs.c).
+The unique codeword index is decoded as a uniformly-distributed integer value between 0 and
+V(N,K)-1, where V(N,K) is the number of possible combinations of K pulses in
+N samples. The index is then converted to a vector in the same way specified in
+<xref target="PVQ"></xref>. The indexing is based on the calculation of V(N,K)
+(denoted N(L,K) in <xref target="PVQ"></xref>).
+</t>
+
+<t>
+ The number of combinations can be computed recursively as
+V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1), with V(N,0) = 1 and V(0,K) = 0, K != 0.
+There are many different ways to compute V(N,K), including precomputed tables and direct
+use of the recursive formulation. The reference implementation applies the recursive
+formulation one line (or column) at a time to save on memory use,
+along with an alternate,
+univariate recurrence to initialize an arbitrary line, and direct
+polynomial solutions for small N. All of these methods are
+equivalent, and have different trade-offs in speed, memory usage, and
+code size. Implementations MAY use any methods they like, as long as
+they are equivalent to the mathematical definition.
+</t>
+
+<t>
+The decoded vector X is recovered as follows.
+Let i be the index decoded with the procedure in <xref target="ec_dec_uint"/>
+ with ft&nbsp;=&nbsp;V(N,K), so that 0&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;V(N,K).
+Let k&nbsp;=&nbsp;K.
+Then for j&nbsp;=&nbsp;0 to (N&nbsp;-&nbsp;1), inclusive, do:
+<list style="numbers">
+<t>Let p&nbsp;=&nbsp;(V(N-j-1,k)&nbsp;+&nbsp;V(N-j,k))/2.</t>
+<t>
+If i&nbsp;&lt;&nbsp;p, then let sgn&nbsp;=&nbsp;1, else let sgn&nbsp;=&nbsp;-1
+ and set i&nbsp;=&nbsp;i&nbsp;-&nbsp;p.
+</t>
+<t>Let k0&nbsp;=&nbsp;k and set p&nbsp;=&nbsp;p&nbsp;-&nbsp;V(N-j-1,k).</t>
+<t>
+While p&nbsp;&gt;&nbsp;i, set k&nbsp;=&nbsp;k&nbsp;-&nbsp;1 and
+ p&nbsp;=&nbsp;p&nbsp;-&nbsp;V(N-j-1,k).
+</t>
+<t>
+Set X[j]&nbsp;=&nbsp;sgn*(k0&nbsp;-&nbsp;k) and i&nbsp;=&nbsp;i&nbsp;-&nbsp;p.
+</t>
+</list>
+</t>
+
+<t>
+The decoded vector X is then normalized such that its
+L2-norm equals one.
+</t>
+</section>
+
+<section anchor="spreading" title="Spreading">
+<t>
+The normalized vector decoded in <xref target="cwrs-decoder"/> is then rotated
+for the purpose of avoiding tonal artifacts. The rotation gain is equal to
+<figure align="center">
+<artwork align="center"><![CDATA[
+g_r = N / (N + f_r*K)
+]]></artwork>
+</figure>
+
+where N is the number of dimensions, K is the number of pulses, and f_r depends on
+the value of the "spread" parameter in the bit-stream.
+</t>
+
+<texttable anchor="spread values" title="Spreading Values">
+<ttcol>Spread value</ttcol>
+<ttcol>f_r</ttcol>
+ <c>0</c> <c>infinite (no rotation)</c>
+ <c>1</c> <c>15</c>
+ <c>2</c> <c>10</c>
+ <c>3</c> <c>5</c>
+</texttable>
+
+<t>
+The rotation angle is then calculated as
+<figure align="center">
+<artwork align="center"><![CDATA[
+                 2
+        pi *  g_r
+theta = ----------
+            4
+]]></artwork>
+</figure>
+A 2-D rotation R(i,j) between points x_i and x_j is defined as:
+<figure align="center">
+<artwork align="center"><![CDATA[
+x_i' =  cos(theta)*x_i + sin(theta)*x_j
+x_j' = -sin(theta)*x_i + cos(theta)*x_j
+]]></artwork>
+</figure>
+
+An N-D rotation is then achieved by applying a series of 2-D rotations back and forth, in the
+following order: R(x_1, x_2), R(x_2, x_3), ..., R(x_N-2, X_N-1), R(x_N-1, X_N),
+R(x_N-2, X_N-1), ..., R(x_1, x_2).
+</t>
+
+<t>
+If the decoded vector represents more
+than one time block, then this spreading process is applied separately on each time block.
+Also, if each block represents 8 samples or more, then another N-D rotation, by
+(pi/2-theta), is applied <spanx style="emph">before</spanx> the rotation described above. This
+extra rotation is applied in an interleaved manner with a stride equal to round(sqrt(N/nb_blocks)),
+i.e., it is applied independently for each set of sample S_k = {stride*n + k}, n=0..N/stride-1.
+</t>
+</section>
+
+<section anchor="split" title="Split decoding">
+<t>
+To avoid the need for multi-precision calculations when decoding PVQ codevectors,
+the maximum size allowed for codebooks is 32 bits. When larger codebooks are
+needed, the vector is instead split in two sub-vectors of size N/2.
+A quantized gain parameter with precision
+derived from the current allocation is entropy coded to represent the relative
+gains of each side of the split, and the entire decoding process is recursively
+applied. Multiple levels of splitting may be applied up to a limit of LM+1 splits.
+The same recursive mechanism is applied for the joint coding
+of stereo audio.
+</t>
+
+</section>
+
+<section anchor="tf-change" title="Time-Frequency change">
+<t>
+The time-frequency (TF) parameters are used to control the time-frequency resolution tradeoff
+in each coded band. For each band, there are two possible TF choices. For the first
+band coded, the PDF is {3, 1}/4 for frames marked as transient and {15, 1}/16 for
+the other frames. For subsequent bands, the TF choice is coded relative to the
+previous TF choice with probability {15, 1}/15 for transient frames and {31, 1}/32
+otherwise. The mapping between the decoded TF choices and the adjustment in TF
+resolution is shown in the tables below.
+</t>
+
+<texttable anchor='tf_00'
+ title="TF Adjustments for Non-transient Frames and tf_select=0">
+<ttcol align='center'>Frame size (ms)</ttcol>
+<ttcol align='center'>0</ttcol>
+<ttcol align='center'>1</ttcol>
+<c>2.5</c>      <c>0</c> <c>-1</c>
+<c>5</c>      <c>0</c> <c>-1</c>
+<c>10</c>      <c>0</c> <c>-2</c>
+<c>20</c>      <c>0</c> <c>-2</c>
+</texttable>
+
+<texttable anchor='tf_01'
+ title="TF Adjustments for Non-transient Frames and tf_select=1">
+<ttcol align='center'>Frame size (ms)</ttcol>
+<ttcol align='center'>0</ttcol>
+<ttcol align='center'>1</ttcol>
+<c>2.5</c>      <c>0</c> <c>-1</c>
+<c>5</c>      <c>0</c> <c>-2</c>
+<c>10</c>      <c>0</c> <c>-3</c>
+<c>20</c>      <c>0</c> <c>-3</c>
+</texttable>
+
+
+<texttable anchor='tf_10'
+ title="TF Adjustments for Transient Frames and tf_select=0">
+<ttcol align='center'>Frame size (ms)</ttcol>
+<ttcol align='center'>0</ttcol>
+<ttcol align='center'>1</ttcol>
+<c>2.5</c>      <c>0</c> <c>-1</c>
+<c>5</c>      <c>1</c> <c>0</c>
+<c>10</c>      <c>2</c> <c>0</c>
+<c>20</c>      <c>3</c> <c>0</c>
+</texttable>
+
+<texttable anchor='tf_11'
+ title="TF Adjustments for Transient Frames and tf_select=1">
+<ttcol align='center'>Frame size (ms)</ttcol>
+<ttcol align='center'>0</ttcol>
+<ttcol align='center'>1</ttcol>
+<c>2.5</c>      <c>0</c> <c>-1</c>
+<c>5</c>      <c>1</c> <c>-1</c>
+<c>10</c>      <c>1</c> <c>-1</c>
+<c>20</c>      <c>1</c> <c>-1</c>
+</texttable>
+
+<t>
+A negative TF adjustment means that the temporal resolution is increased,
+while a positive TF adjustment means that the frequency resolution is increased.
+Changes in TF resolution are implemented using the Hadamard transform <xref target="Hadamard"/>. To increase
+the time resolution by N, N "levels" of the Hadamard transform are applied to the
+decoded vector for each interleaved MDCT vector. To increase the frequency resolution
+(assumes a transient frame), then N levels of the Hadamard transform are applied
+<spanx style="emph">across</spanx> the interleaved MDCT vector. In the case of increased
+time resolution the decoder uses the "sequency order" because the input vector
+is sorted in time.
+</t>
+</section>
+
+
+</section>
+
+<section anchor="anti-collapse" title="Anti-Collapse Processing">
+<t>
+The anti-collapse feature is designed to avoid the situation where the use of multiple
+short MDCTs causes the energy in one or more of the MDCTs to be zero for
+some bands, causing unpleasant artifacts.
+When the frame has the transient bit set, an anti-collapse bit is decoded.
+When anti-collapse is set, the energy in each small MDCT is prevented
+from collapsing to zero. For each band of each MDCT where a collapse is
+detected, a pseudo-random signal is inserted with an energy corresponding
+to the minimum energy over the two previous frames. A renormalization step is
+then required to ensure that the anti-collapse step did not alter the
+energy preservation property.
+</t>
+</section>
+
+<section anchor="denormalization" title="Denormalization">
+<t>
+Just as each band was normalized in the encoder, the last step of the decoder before
+the inverse MDCT is to denormalize the bands. Each decoded normalized band is
+multiplied by the square root of the decoded energy. This is done by denormalise_bands()
+(bands.c).
+</t>
+</section>
+
+<section anchor="inverse-mdct" title="Inverse MDCT">
+
+
+<t>The inverse MDCT implementation has no special characteristics. The
+input is N frequency-domain samples and the output is 2*N time-domain
+samples, while scaling by 1/2. A "low-overlap" window reduces the algorithmic delay.
+It is derived from a basic (full overlap) 240-sample version of the window used by the Vorbis codec:
+<figure align="center">
+<artwork align="center"><![CDATA[
+                                      2
+       /   /pi      /pi   n + 1/2\ \ \
+W(n) = |sin|-- * sin|-- * -------| | | .
+       \   \2       \2       L   / / /
+]]></artwork>
+</figure>
+The low-overlap window is created by zero-padding the basic window and inserting ones in the
+middle, such that the resulting window still satisfies power complementarity <xref target='Princen86'/>.
+The IMDCT and
+windowing are performed by mdct_backward (mdct.c).
+</t>
+
+<section anchor="post-filter" title="Post-filter">
+<t>
+The output of the inverse MDCT (after weighted overlap-add) is sent to the
+post-filter. Although the post-filter is applied at the end, the post-filter
+parameters are encoded at the beginning, just after the silence flag.
+The post-filter can be switched on or off using one bit (logp=1).
+If the post-filter is enabled, then the octave is decoded as an integer value
+between 0 and 6 of uniform probability. Once the octave is known, the fine pitch
+within the octave is decoded using 4+octave raw bits. The final pitch period
+is equal to (16&lt;&lt;octave)+fine_pitch-1 so it is bounded between 15 and 1022,
+inclusively. Next, the gain is decoded as three raw bits and is equal to
+G=3*(int_gain+1)/32. The set of post-filter taps is decoded last, using
+a pdf equal to {2, 1, 1}/4. Tapset zero corresponds to the filter coefficients
+g0 = 0.3066406250, g1 = 0.2170410156, g2 = 0.1296386719. Tapset one
+corresponds to the filter coefficients g0 = 0.4638671875, g1 = 0.2680664062,
+g2 = 0, and tapset two uses filter coefficients g0 = 0.7998046875,
+g1 = 0.1000976562, g2 = 0.
+</t>
+
+<t>
+The post-filter response is thus computed as:
+              <figure align="center">
+                <artwork align="center">
+                  <![CDATA[
+   y(n) = x(n) + G*(g0*y(n-T) + g1*(y(n-T+1)+y(n-T+1))
+                              + g2*(y(n-T+2)+y(n-T+2)))
+]]>
+                </artwork>
+              </figure>
+
+During a transition between different gains, a smooth transition is calculated
+using the square of the MDCT window. It is important that values of y(n) be
+interpolated one at a time such that the past value of y(n) used is interpolated.
+</t>
+</section>
+
+<section anchor="deemphasis" title="De-emphasis">
+<t>
+After the post-filter,
+the signal is de-emphasized using the inverse of the pre-emphasis filter
+used in the encoder:
+<figure align="center">
+<artwork align="center"><![CDATA[
+ 1            1
+---- = --------------- ,
+A(z)                -1
+       1 - alpha_p*z
+]]></artwork>
+</figure>
+where alpha_p=0.8500061035.
+</t>
+</section>
+
+</section>
+
+</section>
+
+<section anchor="Packet Loss Concealment" title="Packet Loss Concealment (PLC)">
+<t>
+Packet loss concealment (PLC) is an optional decoder-side feature that
+SHOULD be included when receiving from an unreliable channel. Because
+PLC is not part of the bitstream, there are many acceptable ways to
+implement PLC with different complexity/quality trade-offs.
+</t>
+
+<t>
+The PLC in
+the reference implementation depends on the mode of last packet received.
+In CELT mode, the PLC finds a periodicity in the decoded
+signal and repeats the windowed waveform using the pitch offset. The windowed
+waveform is overlapped in such a way as to preserve the time-domain aliasing
+cancellation with the previous frame and the next frame. This is implemented
+in celt_decode_lost() (mdct.c).  In SILK mode, the PLC uses LPC extrapolation
+from the previous frame, implemented in silk_PLC() (PLC.c).
+</t>
+
+<section anchor="clock-drift" title="Clock Drift Compensation">
+<t>
+Clock drift refers to the gradual desynchronization of two endpoints
+whose sample clocks run at different frequencies while they are streaming
+live audio.  Differences in clock frequencies are generally attributable to
+manufacturing variation in the endpoints' clock hardware.  For long-lived
+streams, the time difference between sender and receiver can grow without
+bound.
+</t>
+
+<t>
+When the sender's clock runs slower than the receiver's, the effect is similar
+to packet loss: too few packets are received.  The receiver can distinguish
+between drift and loss if the transport provides packet timestamps.  A receiver
+for live streams SHOULD conceal the effects of drift, and MAY do so by invoking
+the PLC.
+</t>
+
+<t>
+When the sender's clock runs faster than the receiver's, too many packets will
+be received.  The receiver MAY respond by skipping any packet (i.e., not
+submitting the packet for decoding).  This is likely to produce a less severe
+artifact than if the frame were dropped after decoding.
+</t>
+
+<t>
+A decoder MAY employ a more sophisticated drift compensation method. For
+example, the
+<xref target='Google-NetEQ'>NetEQ component</xref>
+of the
+<xref target='Google-WebRTC'>Google WebRTC codebase</xref>
+compensates for drift by adding or removing
+one period when the signal is highly periodic. The reference implementation of
+Opus allows a caller to learn whether the current frame's signal is highly
+periodic, and if so what the period is, using the OPUS_GET_PITCH() request.
+</t>
+</section>
+
+</section>
+
+<section anchor="switching" title="Configuration Switching">
+
+<t>
+Switching between the Opus coding modes, audio bandwidths, and channel counts
+ requires careful consideration to avoid audible glitches.
+Switching between any two configurations of the CELT-only mode, any two
+ configurations of the Hybrid mode, or from WB SILK to Hybrid mode does not
+ require any special treatment in the decoder, as the MDCT overlap will smooth
+ the transition.
+Switching from Hybrid mode to WB SILK requires adding in the final contents
+ of the CELT overlap buffer to the first SILK-only packet.
+This can be done by decoding a 2.5&nbsp;ms silence frame with the CELT decoder
+ using the channel count of the SILK-only packet (and any choice of audio
+ bandwidth), which will correctly handle the cases when the channel count
+ changes as well.
+</t>
+
+<t>
+When changing the channel count for SILK-only or Hybrid packets, the encoder
+ can avoid glitches by smoothly varying the stereo width of the input signal
+ before or after the transition, and SHOULD do so.
+However, other transitions between SILK-only packets or between NB or MB SILK
+ and Hybrid packets may cause glitches, because neither the LSF coefficients
+ nor the LTP, LPC, stereo unmixing, and resampler buffers are available at the
+ new sample rate.
+These switches SHOULD be delayed by the encoder until quiet periods or
+ transients, where the inevitable glitches will be less audible. Additionally,
+ the bit-stream MAY include redundant side information ("redundancy"), in the
+ form of additional CELT frames embedded in each of the Opus frames around the
+ transition.
+</t>
+
+<t>
+The other transitions that cannot be easily handled are those where the lower
+ frequencies switch between the SILK LP-based model and the CELT MDCT model.
+However, an encoder may not have an opportunity to delay such a switch to a
+ convenient point.
+For example, if the content switches from speech to music, and the encoder does
+ not have enough latency in its analysis to detect this in advance, there may
+ be no convenient silence period during which to make the transition for quite
+ some time.
+To avoid or reduce glitches during these problematic mode transitions, and
+ also between audio bandwidth changes in the SILK-only modes, transitions MAY
+ include redundant side information ("redundancy"), in the form of an
+ additional CELT frame embedded in the Opus frame.
+</t>
+
+<t>
+A transition between coding the lower frequencies with the LP model and the
+ MDCT model or a transition that involves changing the SILK bandwidth
+ is only normatively specified when it includes redundancy.
+For those without redundancy, it is RECOMMENDED that the decoder use a
+ concealment technique (e.g., make use of a PLC algorithm) to "fill in" the
+ gap or discontinuity caused by the mode transition.
+Therefore, PLC MUST NOT be applied during any normative transition, i.e., when
+<list style="symbols">
+<t>A packet includes redundancy for this transition (as described below),</t>
+<t>The transition is between any WB SILK packet and any Hybrid packet, or vice
+ versa,</t>
+<t>The transition is between any two Hybrid mode packets, or</t>
+<t>The transition is between any two CELT mode packets,</t>
+</list>
+ unless there is actual packet loss.
+</t>
+
+<section anchor="side-info" title="Transition Side Information (Redundancy)">
+<t>
+Transitions with side information include an extra 5&nbsp;ms "redundant" CELT
+ frame within the Opus frame.
+This frame is designed to fill in the gap or discontinuity in the different
+ layers without requiring the decoder to conceal it.
+For transitions from CELT-only to SILK-only or Hybrid, the redundant frame is
+ inserted in the first Opus frame after the transition (i.e., the first
+ SILK-only or Hybrid frame).
+For transitions from SILK-only or Hybrid to CELT-only, the redundant frame is
+ inserted in the last Opus frame before the transition (i.e., the last
+ SILK-only or Hybrid frame).
+</t>
+
+<section anchor="opus_redundancy_flag" title="Redundancy Flag">
+<t>
+The presence of redundancy is signaled in all SILK-only and Hybrid frames, not
+ just those involved in a mode transition.
+This allows the frames to be decoded correctly even if an adjacent frame is
+ lost.
+For SILK-only frames, this signaling is implicit, based on the size of the
+ of the Opus frame and the number of bits consumed decoding the SILK portion of
+ it.
+After decoding the SILK portion of the Opus frame, the decoder uses ec_tell()
+ (see <xref target="ec_tell"/>) to check if there are at least 17 bits
+ remaining.
+If so, then the frame contains redundancy.
+</t>
+
+<t>
+For Hybrid frames, this signaling is explicit.
+After decoding the SILK portion of the Opus frame, the decoder uses ec_tell()
+ (see <xref target="ec_tell"/>) to ensure there are at least 37 bits remaining.
+If so, it reads a symbol with the PDF in
+ <xref target="opus_redundancy_flag_pdf"/>, and if the value is 1, then the
+ frame contains redundancy.
+Otherwise (if there were fewer than 37 bits left or the value was 0), the frame
+ does not contain redundancy.
+</t>
+
+<texttable anchor="opus_redundancy_flag_pdf" title="Redundancy Flag PDF">
+<ttcol>PDF</ttcol>
+<c>{4095, 1}/4096</c>
+</texttable>
+</section>
+
+<section anchor="opus_redundancy_pos" title="Redundancy Position Flag">
+<t>
+Since the current frame is a SILK-only or a Hybrid frame, it must be at least
+ 10&nbsp;ms.
+Therefore, it needs an additional flag to indicate whether the redundant
+ 5&nbsp;ms CELT frame should be mixed into the beginning of the current frame,
+ or the end.
+After determining that a frame contains redundancy, the decoder reads a
+ 1&nbsp;bit symbol with a uniform PDF
+ (<xref target="opus_redundancy_pos_pdf"/>).
+</t>
+
+<texttable anchor="opus_redundancy_pos_pdf" title="Redundancy Position PDF">
+<ttcol>PDF</ttcol>
+<c>{1, 1}/2</c>
+</texttable>
+
+<t>
+If the value is zero, this is the first frame in the transition, and the
+ redundancy belongs at the end.
+If the value is one, this is the second frame in the transition, and the
+ redundancy belongs at the beginning.
+There is no way to specify that an Opus frame contains separate redundant CELT
+ frames at both the beginning and the end.
+</t>
+</section>
+
+<section anchor="opus_redundancy_size" title="Redundancy Size">
+<t>
+Unlike the CELT portion of a Hybrid frame, the redundant CELT frame does not
+ use the same entropy coder state as the rest of the Opus frame, because this
+ would break the CELT bit allocation mechanism in Hybrid frames.
+Thus, a redundant CELT frame always starts and ends on a byte boundary, even in
+ SILK-only frames, where this is not strictly necessary.
+</t>
+
+<t>
+For SILK-only frames, the number of bytes in the redundant CELT frame is simply
+ the number of whole bytes remaining, which must be at least 2, due to the
+ space check in <xref target="opus_redundancy_flag"/>.
+For Hybrid frames, the number of bytes is equal to 2, plus a decoded unsigned
+ integer less than 256 (see <xref target="ec_dec_uint"/>).
+This may be more than the number of whole bytes remaining in the Opus frame,
+ in which case the frame is invalid.
+However, a decoder is not required to ignore the entire frame, as this may be
+ the result of a bit error that desynchronized the range coder.
+There may still be useful data before the error, and a decoder MAY keep any
+ audio decoded so far instead of invoking the PLC, but it is RECOMMENDED that
+ the decoder stop decoding and discard the rest of the current Opus frame.
+</t>
+
+<t>
+It would have been possible to avoid these invalid states in the design of Opus
+ by limiting the range of the explicit length decoded from Hybrid frames by the
+ actual number of whole bytes remaining.
+However, this would require an encoder to determine the rate allocation for the
+ MDCT layer up front, before it began encoding that layer.
+By allowing some invalid sizes, the encoder is able to defer that decision
+ until much later.
+When encoding Hybrid frames which do not include redundancy, the encoder must
+ still decide up-front if it wishes to use the minimum 37 bits required to
+ trigger encoding of the redundancy flag, but this is a much looser
+ restriction.
+</t>
+
+<t>
+After determining the size of the redundant CELT frame, the decoder reduces
+ the size of the buffer currently in use by the range coder by that amount.
+The CELT layer read any raw bits from the end of this reduced buffer, and all
+ calculations of the number of bits remaining in the buffer must be done using
+ this new, reduced size, rather than the original size of the Opus frame.
+</t>
+</section>
+
+<section anchor="opus_redundancy_decoding" title="Decoding the Redundancy">
+<t>
+The redundant frame is decoded like any other CELT-only frame, with the
+ exception that it does not contain a TOC byte.
+The frame size is fixed at 5&nbsp;ms, the channel count is set to that of the
+ current frame, and the audio bandwidth is also set to that of the current
+ frame, with the exception that for MB SILK frames, it is set to WB.
+</t>
+
+<t>
+If the redundancy belongs at the beginning (in a CELT-only to SILK-only or
+ Hybrid transition), the final reconstructed output uses the first 2.5&nbsp;ms
+ of audio output by the decoder for the redundant frame as-is, discarding
+ the corresponding output from the SILK-only or Hybrid portion of the frame.
+The remaining 2.5&nbsp;ms is cross-lapped with the decoded SILK/Hybrid signal
+ using the CELT's power-complementary MDCT window to ensure a smooth
+ transition.
+</t>
+
+<t>
+If the redundancy belongs at the end (in a SILK-only or Hybrid to CELT-only
+ transition), only the second half (2.5&nbsp;ms) of the audio output by the
+ decoder for the redundant frame is used.
+In that case, the second half of the redundant frame is cross-lapped with the
+ end of the SILK/Hybrid signal, again using CELT's power-complementary MDCT
+ window to ensure a smooth transition.
+</t>
+</section>
+
+</section>
+
+<section anchor="decoder-reset" title="State Reset">
+<t>
+When a transition occurs, the state of the SILK or the CELT decoder (or both)
+ may need to be reset before decoding a frame in the new mode.
+This avoids reusing "out of date" memory, which may not have been updated in
+ some time or may not be in a well-defined state due to, e.g., PLC.
+The SILK state is reset before every SILK-only or Hybrid frame where the
+ previous frame was CELT-only.
+The CELT state is reset every time the operating mode changes and the new mode
+ is either Hybrid or CELT-only, except when the transition uses redundancy as
+ described above.
+When switching from SILK-only or Hybrid to CELT-only with redundancy, the CELT
+ state is reset before decoding the redundant CELT frame embedded in the
+ SILK-only or Hybrid frame, but it is not reset before decoding the following
+ CELT-only frame.
+When switching from CELT-only mode to SILK-only or Hybrid mode with redundancy,
+ the CELT decoder is not reset for decoding the redundant CELT frame.
+</t>
+</section>
+
+<section title="Summary of Transitions">
+
+<t>
+<xref target="normative_transitions"/> illustrates all of the normative
+ transitions involving a mode change, an audio bandwidth change, or both.
+Each one uses an S, H, or C to represent an Opus frame in the corresponding
+ mode.
+In addition, an R indicates the presence of redundancy in the Opus frame it is
+ cross-lapped with.
+Its location in the first or last 5&nbsp;ms is assumed to correspond to whether
+ it is the frame before or after the transition.
+Other uses of redundancy are non-normative.
+Finally, a c indicates the contents of the CELT overlap buffer after the
+ previously decoded frame (i.e., as extracted by decoding a silence frame).
+<figure align="center" anchor="normative_transitions"
+ title="Normative Transitions">
+<artwork align="center"><![CDATA[
+SILK to SILK with Redundancy:             S -> S -> S
+                                                    &
+                                                   !R -> R
+                                                         &
+                                                        ;S -> S -> S
+
+NB or MB SILK to Hybrid with Redundancy:  S -> S -> S
+                                                    &
+                                                   !R ->;H -> H -> H
+
+WB SILK to Hybrid:                        S -> S -> S ->!H -> H -> H
+
+SILK to CELT with Redundancy:             S -> S -> S
+                                                    &
+                                                   !R -> C -> C -> C
+
+Hybrid to NB or MB SILK with Redundancy:  H -> H -> H
+                                                    &
+                                                   !R -> R
+                                                         &
+                                                        ;S -> S -> S
+
+Hybrid to WB SILK:                        H -> H -> H -> c
+                                                      \  +
+                                                       > S -> S -> S
+
+Hybrid to CELT with Redundancy:           H -> H -> H
+                                                    &
+                                                   !R -> C -> C -> C
+
+CELT to SILK with Redundancy:             C -> C -> C -> R
+                                                         &
+                                                        ;S -> S -> S
+
+CELT to Hybrid with Redundancy:           C -> C -> C -> R
+                                                         &
+                                                        |H -> H -> H
+
+Key:
+S   SILK-only frame                 ;   SILK decoder reset
+H   Hybrid frame                    |   CELT and SILK decoder resets
+C   CELT-only frame                 !   CELT decoder reset
+c   CELT overlap                    +   Direct mixing
+R   Redundant CELT frame            &   Windowed cross-lap
+]]></artwork>
+</figure>
+The first two and the last two Opus frames in each example are illustrative,
+ i.e., there is no requirement that a stream remain in the same configuration
+ for three consecutive frames before or after a switch.
+</t>
+
+<t>
+The behavior of transitions without redundancy where PLC is allowed is non-normative.
+An encoder might still wish to use these transitions if, for example, it
+ doesn't want to add the extra bitrate required for redundancy or if it makes
+ a decision to switch after it has already transmitted the frame that would
+ have had to contain the redundancy.
+<xref target="nonnormative_transitions"/> illustrates the recommended
+ cross-lapping and decoder resets for these transitions.
+<figure align="center" anchor="nonnormative_transitions"
+ title="Recommended Non-Normative Transitions">
+<artwork align="center"><![CDATA[
+SILK to SILK (audio bandwidth change):    S -> S -> S   ;S -> S -> S
+
+NB or MB SILK to Hybrid:                  S -> S -> S   |H -> H -> H
+
+SILK to CELT without Redundancy:          S -> S -> S -> P
+                                                         &
+                                                        !C -> C -> C
+
+Hybrid to NB or MB SILK:                  H -> H -> H -> c
+                                                         +
+                                                        ;S -> S -> S
+
+Hybrid to CELT without Redundancy:        H -> H -> H -> P
+                                                         &
+                                                        !C -> C -> C
+
+CELT to SILK without Redundancy:          C -> C -> C -> P
+                                                         &
+                                                        ;S -> S -> S
+
+CELT to Hybrid without Redundancy:        C -> C -> C -> P
+                                                         &
+                                                        |H -> H -> H
+
+Key:
+S   SILK-only frame                 ;   SILK decoder reset
+H   Hybrid frame                    |   CELT and SILK decoder resets
+C   CELT-only frame                 !   CELT decoder reset
+c   CELT overlap                    +   Direct mixing
+P   Packet Loss Concealment         &   Windowed cross-lap
+]]></artwork>
+</figure>
+Encoders SHOULD NOT use other transitions, e.g., those that involve redundancy
+ in ways not illustrated in <xref target="normative_transitions"/>.
+</t>
+
+</section>
+
+</section>
+
+</section>
+
+
+<!--  ******************************************************************* -->
+<!--  **************************   OPUS ENCODER   *********************** -->
+<!--  ******************************************************************* -->
+
+<section title="Opus Encoder">
+<t>
+Just like the decoder, the Opus encoder also normally consists of two main blocks: the
+SILK encoder and the CELT encoder. However, unlike the case of the decoder, a valid
+(though potentially suboptimal) Opus encoder is not required to support all modes and
+may thus only include a SILK encoder module or a CELT encoder module.
+The output bit-stream of the Opus encoding contains bits from the SILK and CELT
+ encoders, though these are not separable due to the use of a range coder.
+A block diagram of the encoder is illustrated below.
+
+<figure align="center" anchor="opus-encoder-figure" title="Opus Encoder">
+<artwork>
+<![CDATA[
+                    +------------+    +---------+
+                    |   Sample   |    |  SILK   |------+
+                 +->|    Rate    |--->| Encoder |      V
+  +-----------+  |  | Conversion |    |         | +---------+
+  | Optional  |  |  +------------+    +---------+ |  Range  |
+->| High-pass |--+                                | Encoder |---->
+  |  Filter   |  |  +--------------+  +---------+ |         | Bit-
+  +-----------+  |  |    Delay     |  |  CELT   | +---------+ stream
+                 +->| Compensation |->| Encoder |      ^
+                    |              |  |         |------+
+                    +--------------+  +---------+
+]]>
+</artwork>
+</figure>
+</t>
+
+<t>
+For a normal encoder where both the SILK and the CELT modules are included, an optimal
+encoder should select which coding mode to use at run-time depending on the conditions.
+In the reference implementation, the frame size is selected by the application, but the
+other configuration parameters (number of channels, bandwidth, mode) are automatically
+selected (unless explicitly overridden by the application) depend on the following:
+<list style="symbols">
+<t>Requested bitrate</t>
+<t>Input sampling rate</t>
+<t>Type of signal (speech vs music)</t>
+<t>Frame size in use</t>
+</list>
+
+The type of signal currently needs to be provided by the application (though it can be
+changed in real-time). An Opus encoder implementation could also do automatic detection,
+but since Opus is an interactive codec, such an implementation would likely have to either
+delay the signal (for non-interactive applications) or delay the mode switching decisions (for
+interactive applications).
+</t>
+
+<t>
+When the encoder is configured for voice over IP applications, the input signal is
+filtered by a high-pass filter to remove the lowest part of the spectrum
+that contains little speech energy and may contain background noise. This is a second order
+Auto Regressive Moving Average (i.e., with poles and zeros) filter with a cut-off frequency around 50&nbsp;Hz.
+In the future, a music detector may also be used to lower the cut-off frequency when the
+input signal is detected to be music rather than speech.
+</t>
+
+<section anchor="range-encoder" title="Range Encoder">
+<t>
+The range coder acts as the bit-packer for Opus.
+It is used in three different ways: to encode
+<list style="symbols">
+<t>
+Entropy-coded symbols with a fixed probability model using ec_encode()
+ (entenc.c),
+</t>
+<t>
+Integers from 0 to (2**M&nbsp;-&nbsp;1) using ec_enc_uint() or ec_enc_bits()
+ (entenc.c),</t>
+<t>
+Integers from 0 to (ft&nbsp;-&nbsp;1) (where ft is not a power of two) using
+ ec_enc_uint() (entenc.c).
+</t>
+</list>
+</t>
+
+<t>
+The range encoder maintains an internal state vector composed of the four-tuple
+ (val,&nbsp;rng,&nbsp;rem,&nbsp;ext) representing the low end of the current
+ range, the size of the current range, a single buffered output byte, and a
+ count of additional carry-propagating output bytes.
+Both val and rng are 32-bit unsigned integer values, rem is a byte value or
+ less than 255 or the special value -1, and ext is an unsigned integer with at
+ least 11 bits.
+This state vector is initialized at the start of each each frame to the value
+ (0,&nbsp;2**31,&nbsp;-1,&nbsp;0).
+After encoding a sequence of symbols, the value of rng in the encoder should
+ exactly match the value of rng in the decoder after decoding the same sequence
+ of symbols.
+This is a powerful tool for detecting errors in either an encoder or decoder
+ implementation.
+The value of val, on the other hand, represents different things in the encoder
+ and decoder, and is not expected to match.
+</t>
+
+<t>
+The decoder has no analog for rem and ext.
+These are used to perform carry propagation in the renormalization loop below.
+Each iteration of this loop produces 9 bits of output, consisting of 8 data
+ bits and a carry flag.
+The encoder cannot determine the final value of the output bytes until it
+ propagates these carry flags.
+Therefore the reference implementation buffers a single non-propagating output
+ byte (i.e., one less than 255) in rem and keeps a count of additional
+ propagating (i.e., 255) output bytes in ext.
+An implementation may choose to use any mathematically equivalent scheme to
+ perform carry propagation.
+</t>
+
+<section anchor="encoding-symbols" title="Encoding Symbols">
+<t>
+The main encoding function is ec_encode() (entenc.c), which encodes symbol k in
+ the current context using the same three-tuple (fl[k],&nbsp;fh[k],&nbsp;ft)
+ as the decoder to describe the range of the symbol (see
+ <xref target="range-decoder"/>).
+</t>
+<t>
+ec_encode() updates the state of the encoder as follows.
+If fl[k] is greater than zero, then
+<figure align="center">
+<artwork align="center"><![CDATA[
+                  rng
+val = val + rng - --- * (ft - fl) ,
+                  ft
+
+      rng
+rng = --- * (fh - fl) .
+      ft
+]]></artwork>
+</figure>
+Otherwise, val is unchanged and
+<figure align="center">
+<artwork align="center"><![CDATA[
+            rng
+rng = rng - --- * (fh - fl) .
+            ft
+]]></artwork>
+</figure>
+The divisions here are integer division.
+</t>
+
+<section anchor="range-encoder-renorm" title="Renormalization">
+<t>
+After this update, the range is normalized using a procedure very similar to
+ that of <xref target="range-decoder-renorm"/>, implemented by
+ ec_enc_normalize() (entenc.c).
+The following process is repeated until rng&nbsp;&gt;&nbsp;2**23.
+First, the top 9 bits of val, (val&gt;&gt;23), are sent to the carry buffer,
+ described in <xref target="ec_enc_carry_out"/>.
+Then, the encoder sets
+<figure align="center">
+<artwork align="center"><![CDATA[
+val = (val<<8) & 0x7FFFFFFF ,
+
+rng = rng<<8 .
+]]></artwork>
+</figure>
+</t>
+</section>
+
+<section anchor="ec_enc_carry_out"
+ title="Carry Propagation and Output Buffering">
+<t>
+The function ec_enc_carry_out() (entenc.c) implements carry propagation and
+ output buffering.
+It takes as input a 9-bit value, c, consisting of 8 data bits and an additional
+ carry bit.
+If c is equal to the value 255, then ext is simply incremented, and no other
+ state updates are performed.
+Otherwise, let b&nbsp;=&nbsp;(c&gt;&gt;8) be the carry bit.
+Then,
+<list style="symbols">
+<t>
+If the buffered byte rem contains a value other than -1, the encoder outputs
+ the byte (rem&nbsp;+&nbsp;b).
+Otherwise, if rem is -1, no byte is output.
+</t>
+<t>
+If ext is non-zero, then the encoder outputs ext bytes---all with a value of 0
+ if b is set, or 255 if b is unset---and sets ext to 0.
+</t>
+<t>
+rem is set to the 8 data bits:
+<figure align="center">
+<artwork align="center"><![CDATA[
+rem = c & 255 .
+]]></artwork>
+</figure>
+</t>
+</list>
+</t>
+</section>
+
+</section>
+
+<section anchor="encoding-alternate" title="Alternate Encoding Methods">
+<t>
+The reference implementation uses three additional encoding methods that are
+ exactly equivalent to the above, but make assumptions and simplifications that
+ allow for a more efficient implementation.
+</t>
+
+<section anchor="ec_encode_bin" title="ec_encode_bin()">
+<t>
+The first is ec_encode_bin() (entenc.c), defined using the parameter ftb
+ instead of ft.
+It is mathematically equivalent to calling ec_encode() with
+ ft&nbsp;=&nbsp;(1&lt;&lt;ftb), but avoids using division.
+</t>
+</section>
+
+<section anchor="ec_enc_bit_logp" title="ec_enc_bit_logp()">
+<t>
+The next is ec_enc_bit_logp() (entenc.c), which encodes a single binary symbol.
+The context is described by a single parameter, logp, which is the absolute
+ value of the base-2 logarithm of the probability of a "1".
+It is mathematically equivalent to calling ec_encode() with the 3-tuple
+ (fl[k]&nbsp;=&nbsp;0, fh[k]&nbsp;=&nbsp;(1&lt;&lt;logp)&nbsp;-&nbsp;1,
+ ft&nbsp;=&nbsp;(1&lt;&lt;logp)) if k is 0 and with
+ (fl[k]&nbsp;=&nbsp;(1&lt;&lt;logp)&nbsp;-&nbsp;1,
+ fh[k]&nbsp;=&nbsp;ft&nbsp;=&nbsp;(1&lt;&lt;logp)) if k is 1.
+The implementation requires no multiplications or divisions.
+</t>
+</section>
+
+<section anchor="ec_enc_icdf" title="ec_enc_icdf()">
+<t>
+The last is ec_enc_icdf() (entenc.c), which encodes a single binary symbol with
+ a table-based context of up to 8 bits.
+This uses the same icdf table as ec_dec_icdf() from
+ <xref target="ec_dec_icdf"/>.
+The function is mathematically equivalent to calling ec_encode() with
+ fl[k]&nbsp;=&nbsp;(1&lt;&lt;ftb)&nbsp;-&nbsp;icdf[k-1] (or 0 if
+ k&nbsp;==&nbsp;0), fh[k]&nbsp;=&nbsp;(1&lt;&lt;ftb)&nbsp;-&nbsp;icdf[k], and
+ ft&nbsp;=&nbsp;(1&lt;&lt;ftb).
+This only saves a few arithmetic operations over ec_encode_bin(), but allows
+ the encoder to use the same icdf tables as the decoder.
+</t>
+</section>
+
+</section>
+
+<section anchor="encoding-bits" title="Encoding Raw Bits">
+<t>
+The raw bits used by the CELT layer are packed at the end of the buffer using
+ ec_enc_bits() (entenc.c).
+Because the raw bits may continue into the last byte output by the range coder
+ if there is room in the low-order bits, the encoder must be prepared to merge
+ these values into a single byte.
+The procedure in <xref target="encoder-finalizing"/> does this in a way that
+ ensures both the range coded data and the raw bits can be decoded
+ successfully.
+</t>
+</section>
+
+<section anchor="encoding-ints" title="Encoding Uniformly Distributed Integers">
+<t>
+The function ec_enc_uint() (entenc.c) encodes one of ft equiprobable symbols in
+ the range 0 to (ft&nbsp;-&nbsp;1), inclusive, each with a frequency of 1,
+ where ft may be as large as (2**32&nbsp;-&nbsp;1).
+Like the decoder (see <xref target="ec_dec_uint"/>), it splits up the
+ value into a range coded symbol representing up to 8 of the high bits, and, if
+ necessary, raw bits representing the remainder of the value.
+</t>
+<t>
+ec_enc_uint() takes a two-tuple (t,&nbsp;ft), where t is the value to be
+ encoded, 0&nbsp;&lt;=&nbsp;t&nbsp;&lt;&nbsp;ft, and ft is not necessarily a
+ power of two.
+Let ftb&nbsp;=&nbsp;ilog(ft&nbsp;-&nbsp;1), i.e., the number of bits required
+ to store (ft&nbsp;-&nbsp;1) in two's complement notation.
+If ftb is 8 or less, then t is encoded directly using ec_encode() with the
+ three-tuple (t, t&nbsp;+&nbsp;1, ft).
+</t>
+<t>
+If ftb is greater than 8, then the top 8 bits of t are encoded using the
+ three-tuple (t&gt;&gt;(ftb&nbsp;-&nbsp;8),
+ (t&gt;&gt;(ftb&nbsp;-&nbsp;8))&nbsp;+&nbsp;1,
+ ((ft&nbsp;-&nbsp;1)&gt;&gt;(ftb&nbsp;-&nbsp;8))&nbsp;+&nbsp;1), and the
+ remaining bits,
+ (t&nbsp;&amp;&nbsp;((1&lt;&lt;(ftb&nbsp;-&nbsp;8))&nbsp;-&nbsp;1),
+ are encoded as raw bits with ec_enc_bits().
+</t>
+</section>
+
+<section anchor="encoder-finalizing" title="Finalizing the Stream">
+<t>
+After all symbols are encoded, the stream must be finalized by outputting a
+ value inside the current range.
+Let end be the integer in the interval [val,&nbsp;val&nbsp;+&nbsp;rng) with the
+ largest number of trailing zero bits, b, such that
+ (end&nbsp;+&nbsp;(1&lt;&lt;b)&nbsp;-&nbsp;1) is also in the interval
+ [val,&nbsp;val&nbsp;+&nbsp;rng).
+This choice of end allows the maximum number of trailing bits to be set to
+ arbitrary values while still ensuring the range coded part of the buffer can
+ be decoded correctly.
+Then, while end is not zero, the top 9 bits of end, i.e., (end&gt;&gt;23), are
+ passed to the carry buffer in accordance with the procedure in
+ <xref target="ec_enc_carry_out"/>, and end is updated via
+<figure align="center">
+<artwork align="center"><![CDATA[
+end = (end<<8) & 0x7FFFFFFF .
+]]></artwork>
+</figure>
+Finally, if the buffered output byte, rem, is neither zero nor the special
+ value -1, or the carry count, ext, is greater than zero, then 9 zero bits are
+ sent to the carry buffer to flush it to the output buffer.
+When outputting the final byte from the range coder, if it would overlap any
+ raw bits already packed into the end of the output buffer, they should be ORed
+ into the same byte.
+The bit allocation routines in the CELT layer should ensure that this can be
+ done without corrupting the range coder data so long as end is chosen as
+ described above.
+If there is any space between the end of the range coder data and the end of
+ the raw bits, it is padded with zero bits.
+This entire process is implemented by ec_enc_done() (entenc.c).
+</t>
+</section>
+
+<section anchor="encoder-tell" title="Current Bit Usage">
+<t>
+   The bit allocation routines in Opus need to be able to determine a
+   conservative upper bound on the number of bits that have been used
+   to encode the current frame thus far. This drives allocation
+   decisions and ensures that the range coder and raw bits will not
+   overflow the output buffer. This is computed in the
+   reference implementation to whole-bit precision by
+   the function ec_tell() (entcode.h) and to fractional 1/8th bit
+   precision by the function ec_tell_frac() (entcode.c).
+   Like all operations in the range coder, it must be implemented in a
+   bit-exact manner, and must produce exactly the same value returned by
+   the same functions in the decoder after decoding the same symbols.
+</t>
+</section>
+
+</section>
+
+<section title='SILK Encoder'>
+  <t>
+    In many respects the SILK encoder mirrors the SILK decoder described
+    in <xref target='silk_decoder_outline'/>.
+    Details such as the quantization and range coder tables can be found
+    there, while this section describes the high-level design choices that
+    were made.
+    The diagram below shows the basic modules of the SILK encoder.
+<figure align="center" anchor="silk_encoder_figure" title="SILK Encoder">
+<artwork>
+<![CDATA[
+       +----------+    +--------+    +---------+
+       |  Sample  |    | Stereo |    |  SILK   |
+------>|   Rate   |--->| Mixing |--->|  Core   |---------->
+Input  |Conversion|    |        |    | Encoder |  Bitstream
+       +----------+    +--------+    +---------+
+]]>
+</artwork>
+</figure>
+</t>
+
+<section title='Sample Rate Conversion'>
+<t>
+The input signal's sampling rate is adjusted by a sample rate conversion
+module so that it matches the SILK internal sampling rate.
+The input to the sample rate converter is delayed by a number of samples
+depending on the sample rate ratio, such that the overall delay is constant
+for all input and output sample rates.
+</t>
+</section>
+
+<section title='Stereo Mixing'>
+<t>
+The stereo mixer is only used for stereo input signals.
+It converts a stereo left/right signal into an adaptive
+mid/side representation.
+The first step is to compute non-adaptive mid/side signals
+as half the sum and difference between left and right signals.
+The side signal is then minimized in energy by subtracting a
+prediction of it based on the mid signal.
+This prediction works well when the left and right signals
+exhibit linear dependency, for instance for an amplitude-panned
+input signal.
+Like in the decoder, the prediction coefficients are linearly
+interpolated during the first 8&nbsp;ms of the frame.
+  The mid signal is always encoded, whereas the residual
+  side signal is only encoded if it has sufficient
+  energy compared to the mid signal's energy.
+  If it has not,
+  the "mid_only_flag" is set without encoding the side signal.
+</t>
+<t>
+The predictor coefficients are coded regardless of whether
+the side signal is encoded.
+For each frame, two predictor coefficients are computed, one
+that predicts between low-passed mid and side channels, and
+one that predicts between high-passed mid and side channels.
+The low-pass filter is a simple three-tap filter
+and creates a delay of one sample.
+The high-pass filtered signal is the difference between
+the mid signal delayed by one sample and the low-passed
+signal.  Instead of explicitly computing the high-passed
+signal, it is computationally more efficient to transform
+the prediction coefficients before applying them to the
+filtered mid signal, as follows
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+pred(n) = LP(n) * w0 + HP(n) * w1
+        = LP(n) * w0 + (mid(n-1) - LP(n)) * w1
+        = LP(n) * (w0 - w1) + mid(n-1) * w1
+]]>
+</artwork>
+</figure>
+where w0 and w1 are the low-pass and high-pass prediction
+coefficients, mid(n-1) is the mid signal delayed by one sample,
+LP(n) and HP(n) are the low-passed and high-passed
+signals and pred(n) is the prediction signal that is subtracted
+from the side signal.
+</t>
+</section>
+
+<section title='SILK Core Encoder'>
+<t>
+What follows is a description of the core encoder and its components.
+For simplicity, the core encoder is referred to simply as the encoder in
+the remainder of this section. An overview of the encoder is given in
+<xref target="encoder_figure" />.
+</t>
+<figure align="center" anchor="encoder_figure" title="SILK Core Encoder">
+<artwork align="center">
+<![CDATA[
+                                                             +---+
+                          +--------------------------------->|   |
+     +---------+          |      +---------+                 |   |
+     |Voice    |          |      |LTP      |12               |   |
+ +-->|Activity |--+       +----->|Scaling  |-----------+---->|   |
+ |   |Detector |3 |       |      |Control  |<--+       |     |   |
+ |   +---------+  |       |      +---------+   |       |     |   |
+ |                |       |      +---------+   |       |     |   |
+ |                |       |      |Gains    |   |       |     |   |
+ |                |       |  +-->|Processor|---|---+---|---->| R |
+ |                |       |  |   |         |11 |   |   |     | a |
+ |               \/       |  |   +---------+   |   |   |     | n |
+ |          +---------+   |  |   +---------+   |   |   |     | g |
+ |          |Pitch    |   |  |   |LSF      |   |   |   |     | e |
+ |       +->|Analysis |---+  |   |Quantizer|---|---|---|---->|   |
+ |       |  |         |4  |  |   |         |8  |   |   |     | E |-->
+ |       |  +---------+   |  |   +---------+   |   |   |     | n | 2
+ |       |                |  |    9/\  10|     |   |   |     | c |
+ |       |                |  |     |    \/     |   |   |     | o |
+ |       |  +---------+   |  |   +----------+  |   |   |     | d |
+ |       |  |Noise    |   +--|-->|Prediction|--+---|---|---->| e |
+ |       +->|Shaping  |---|--+   |Analysis  |7 |   |   |     | r |
+ |       |  |Analysis |5  |  |   |          |  |   |   |     |   |
+ |       |  +---------+   |  |   +----------+  |   |   |     |   |
+ |       |                |  |        /\       |   |   |     |   |
+ |       |     +----------|--|--------+        |   |   |     |   |
+ |       |     |         \/  \/               \/  \/  \/     |   |
+ |       |     |       +---------+          +------------+   |   |
+ |       |     |       |         |          |Noise       |   |   |
+-+-------+-----+------>|Prefilter|--------->|Shaping     |-->|   |
+1                      |         | 6        |Quantization|13 |   |
+                       +---------+          +------------+   +---+
+
+1:  Input speech signal
+2:  Range encoded bitstream
+3:  Voice activity estimate
+4:  Pitch lags (per 5 ms) and voicing decision (per 20 ms)
+5:  Noise shaping quantization coefficients
+  - Short term synthesis and analysis
+    noise shaping coefficients (per 5 ms)
+  - Long term synthesis and analysis noise
+    shaping coefficients (per 5 ms and for voiced speech only)
+  - Noise shaping tilt (per 5 ms)
+  - Quantizer gain/step size (per 5 ms)
+6:  Input signal filtered with analysis noise shaping filters
+7:  Short and long term prediction coefficients
+    LTP (per 5 ms) and LPC (per 20 ms)
+8:  LSF quantization indices
+9:  LSF coefficients
+10: Quantized LSF coefficients
+11: Processed gains, and synthesis noise shape coefficients
+12: LTP state scaling coefficient. Controlling error propagation
+   / prediction gain trade-off
+13: Quantized signal
+]]>
+</artwork>
+</figure>
+
+<section title='Voice Activity Detection'>
+<t>
+The input signal is processed by a Voice Activity Detector (VAD) to produce
+a measure of voice activity, spectral tilt, and signal-to-noise estimates for
+each frame. The VAD uses a sequence of half-band filterbanks to split the
+signal into four subbands: 0...Fs/16, Fs/16...Fs/8, Fs/8...Fs/4, and
+Fs/4...Fs/2, where Fs is the sampling frequency (8, 12, 16, or 24&nbsp;kHz).
+The lowest subband, from 0 - Fs/16, is high-pass filtered with a first-order
+moving average (MA) filter (with transfer function H(z) = 1-z**(-1)) to
+reduce the energy at the lowest frequencies. For each frame, the signal
+energy per subband is computed.
+In each subband, a noise level estimator tracks the background noise level
+and a Signal-to-Noise Ratio (SNR) value is computed as the logarithm of the
+ratio of energy to noise level.
+Using these intermediate variables, the following parameters are calculated
+for use in other SILK modules:
+<list style="symbols">
+<t>
+Average SNR. The average of the subband SNR values.
+</t>
+
+<t>
+Smoothed subband SNRs. Temporally smoothed subband SNR values.
+</t>
+
+<t>
+Speech activity level. Based on the average SNR and a weighted average of the
+subband energies.
+</t>
+
+<t>
+Spectral tilt. A weighted average of the subband SNRs, with positive weights
+for the low subbands and negative weights for the high subbands.
+</t>
+</list>
+</t>
+</section>
+
+<section title='Pitch Analysis' anchor='pitch_estimator_overview_section'>
+<t>
+The input signal is processed by the open loop pitch estimator shown in
+<xref target='pitch_estimator_figure' />.
+<figure align="center" anchor="pitch_estimator_figure"
+ title="Block diagram of the pitch estimator">
+<artwork align="center">
+<![CDATA[
+                                 +--------+  +----------+
+                                 |2 x Down|  |Time-     |
+                              +->|sampling|->|Correlator|     |
+                              |  |        |  |          |     |4
+                              |  +--------+  +----------+    \/
+                              |                    | 2    +-------+
+                              |                    |  +-->|Speech |5
+    +---------+    +--------+ |                   \/  |   |Type   |->
+    |LPC      |    |Down    | |              +----------+ |       |
+ +->|Analysis | +->|sample  |-+------------->|Time-     | +-------+
+ |  |         | |  |to 8 kHz|                |Correlator|----------->
+ |  +---------+ |  +--------+                |__________|          6
+ |       |      |                                  |3
+ |      \/      |                                 \/
+ |  +---------+ |                            +----------+
+ |  |Whitening| |                            |Time-     |
+-+->|Filter   |-+--------------------------->|Correlator|----------->
+1   |         |                              |          |          7
+    +---------+                              +----------+
+
+1: Input signal
+2: Lag candidates from stage 1
+3: Lag candidates from stage 2
+4: Correlation threshold
+5: Voiced/unvoiced flag
+6: Pitch correlation
+7: Pitch lags
+]]>
+</artwork>
+</figure>
+The pitch analysis finds a binary voiced/unvoiced classification, and, for
+frames classified as voiced, four pitch lags per frame - one for each
+5&nbsp;ms subframe - and a pitch correlation indicating the periodicity of
+the signal.
+The input is first whitened using a Linear Prediction (LP) whitening filter,
+where the coefficients are computed through standard Linear Prediction Coding
+(LPC) analysis. The order of the whitening filter is 16 for best results, but
+is reduced to 12 for medium complexity and 8 for low complexity modes.
+The whitened signal is analyzed to find pitch lags for which the time
+correlation is high.
+The analysis consists of three stages for reducing the complexity:
+<list style="symbols">
+<t>In the first stage, the whitened signal is downsampled to 4&nbsp;kHz
+(from 8&nbsp;kHz) and the current frame is correlated to a signal delayed
+by a range of lags, starting from a shortest lag corresponding to
+500&nbsp;Hz, to a longest lag corresponding to 56&nbsp;Hz.</t>
+
+<t>
+The second stage operates on an 8&nbsp;kHz signal (downsampled from 12, 16,
+or 24&nbsp;kHz) and measures time correlations only near the lags
+corresponding to those that had sufficiently high correlations in the first
+stage. The resulting correlations are adjusted for a small bias towards
+short lags to avoid ending up with a multiple of the true pitch lag.
+The highest adjusted correlation is compared to a threshold depending on:
+<list style="symbols">
+<t>
+Whether the previous frame was classified as voiced
+</t>
+<t>
+The speech activity level
+</t>
+<t>
+The spectral tilt.
+</t>
+</list>
+If the threshold is exceeded, the current frame is classified as voiced and
+the lag with the highest adjusted correlation is stored for a final pitch
+analysis of the highest precision in the third stage.
+</t>
+<t>
+The last stage operates directly on the whitened input signal to compute time
+correlations for each of the four subframes independently in a narrow range
+around the lag with highest correlation from the second stage.
+</t>
+</list>
+</t>
+</section>
+
+<section title='Noise Shaping Analysis' anchor='noise_shaping_analysis_overview_section'>
+<t>
+The noise shaping analysis finds gains and filter coefficients used in the
+prefilter and noise shaping quantizer. These parameters are chosen such that
+they will fulfill several requirements:
+<list style="symbols">
+<t>
+Balancing quantization noise and bitrate.
+The quantization gains determine the step size between reconstruction levels
+of the excitation signal. Therefore, increasing the quantization gain
+amplifies quantization noise, but also reduces the bitrate by lowering
+the entropy of the quantization indices.
+</t>
+<t>
+Spectral shaping of the quantization noise; the noise shaping quantizer is
+capable of reducing quantization noise in some parts of the spectrum at the
+cost of increased noise in other parts without substantially changing the
+bitrate.
+By shaping the noise such that it follows the signal spectrum, it becomes
+less audible. In practice, best results are obtained by making the shape
+of the noise spectrum slightly flatter than the signal spectrum.
+</t>
+<t>
+De-emphasizing spectral valleys; by using different coefficients in the
+analysis and synthesis part of the prefilter and noise shaping quantizer,
+the levels of the spectral valleys can be decreased relative to the levels
+of the spectral peaks such as speech formants and harmonics.
+This reduces the entropy of the signal, which is the difference between the
+coded signal and the quantization noise, thus lowering the bitrate.
+</t>
+<t>
+Matching the levels of the decoded speech formants to the levels of the
+original speech formants; an adjustment gain and a first order tilt
+coefficient are computed to compensate for the effect of the noise
+shaping quantization on the level and spectral tilt.
+</t>
+</list>
+</t>
+<t>
+<figure align="center" anchor="noise_shape_analysis_spectra_figure"
+ title="Noise shaping and spectral de-emphasis illustration">
+<artwork align="center">
+<![CDATA[
+  / \   ___
+   |   // \\
+   |  //   \\     ____
+   |_//     \\___//  \\         ____
+   | /  ___  \   /    \\       //  \\
+ P |/  /   \  \_/      \\_____//    \\
+ o |  /     \     ____  \     /      \\
+ w | /       \___/    \  \___/  ____  \\___ 1
+ e |/                  \       /    \  \
+ r |                    \_____/      \  \__ 2
+   |                                  \
+   |                                   \___ 3
+   |
+   +---------------------------------------->
+                    Frequency
+
+1: Input signal spectrum
+2: De-emphasized and level matched spectrum
+3: Quantization noise spectrum
+]]>
+</artwork>
+</figure>
+<xref target='noise_shape_analysis_spectra_figure' /> shows an example of an
+input signal spectrum (1).
+After de-emphasis and level matching, the spectrum has deeper valleys (2).
+The quantization noise spectrum (3) more or less follows the input signal
+spectrum, while having slightly less pronounced peaks.
+The entropy, which provides a lower bound on the bitrate for encoding the
+excitation signal, is proportional to the area between the de-emphasized
+spectrum (2) and the quantization noise spectrum (3). Without de-emphasis,
+the entropy is proportional to the area between input spectrum (1) and
+quantization noise (3) - clearly higher.
+</t>
+
+<t>
+The transformation from input signal to de-emphasized signal can be
+described as a filtering operation with a filter
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+                           -1    Wana(z)
+H(z) = G * ( 1 - c_tilt * z  ) * -------
+                                 Wsyn(z),
+]]>
+</artwork>
+</figure>
+having an adjustment gain G, a first order tilt adjustment filter with
+tilt coefficient c_tilt, and where
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+               16                            d
+               __             -k        -L  __            -k
+Wana(z) = (1 - \ (a_ana(k) * z  )*(1 - z  * \ b_ana(k) * z  ),
+               /_                           /_
+               k=1                          k=-d
+]]>
+</artwork>
+</figure>
+is the analysis part of the de-emphasis filter, consisting of the short-term
+shaping filter with coefficients a_ana(k), and the long-term shaping filter
+with coefficients b_ana(k) and pitch lag L.
+The parameter d determines the number of long-term shaping filter taps.
+</t>
+
+<t>
+Similarly, but without the tilt adjustment, the synthesis part can be written as
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+               16                            d
+               __             -k        -L  __            -k
+Wsyn(z) = (1 - \ (a_syn(k) * z  )*(1 - z  * \ b_syn(k) * z  ).
+               /_                           /_
+               k=1                          k=-d
+            ]]>
+</artwork>
+</figure>
+</t>
+<t>
+All noise shaping parameters are computed and applied per subframe of 5&nbsp;ms.
+First, an LPC analysis is performed on a windowed signal block of 15&nbsp;ms.
+The signal block has a look-ahead of 5&nbsp;ms relative to the current subframe,
+and the window is an asymmetric sine window. The LPC analysis is done with the
+autocorrelation method, with an order of between 8, in lowest-complexity mode,
+and 16, for best quality.
+</t>
+<t>
+Optionally the LPC analysis and noise shaping filters are warped by replacing
+the delay elements by first-order allpass filters.
+This increases the frequency resolution at low frequencies and reduces it at
+high ones, which better matches the human auditory system and improves
+quality.
+The warped analysis and filtering comes at a cost in complexity
+and is therefore only done in higher complexity modes.
+</t>
+<t>
+The quantization gain is found by taking the square root of the residual energy
+from the LPC analysis and multiplying it by a value inversely proportional
+to the coding quality control parameter and the pitch correlation.
+</t>
+<t>
+Next the two sets of short-term noise shaping coefficients a_ana(k) and
+a_syn(k) are obtained by applying different amounts of bandwidth expansion to the
+coefficients found in the LPC analysis.
+This bandwidth expansion moves the roots of the LPC polynomial towards the
+origin, using the formulas
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+                      k
+ a_ana(k) = a(k)*g_ana , and
+
+                      k
+ a_syn(k) = a(k)*g_syn ,
+]]>
+</artwork>
+</figure>
+where a(k) is the k'th LPC coefficient, and the bandwidth expansion factors
+g_ana and g_syn are calculated as
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+g_ana = 0.95 - 0.01*C, and
+
+g_syn = 0.95 + 0.01*C,
+]]>
+</artwork>
+</figure>
+where C is the coding quality control parameter between 0 and 1.
+Applying more bandwidth expansion to the analysis part than to the synthesis
+part gives the desired de-emphasis of spectral valleys in between formants.
+</t>
+
+<t>
+The long-term shaping is applied only during voiced frames.
+It uses three filter taps, described by
+<figure align="center">
+<artwork align="center">
+  <![CDATA[
+b_ana = F_ana * [0.25, 0.5, 0.25], and
+
+b_syn = F_syn * [0.25, 0.5, 0.25].
+]]>
+</artwork>
+</figure>
+For unvoiced frames these coefficients are set to 0. The multiplication factors
+F_ana and F_syn are chosen between 0 and 1, depending on the coding quality
+control parameter, as well as the calculated pitch correlation and smoothed
+subband SNR of the lowest subband. By having F_ana less than F_syn,
+the pitch harmonics are emphasized relative to the valleys in between the
+harmonics.
+</t>
+
+<t>
+The tilt coefficient c_tilt is for unvoiced frames chosen as
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+c_tilt = 0.25,
+]]>
+</artwork>
+</figure>
+and as
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+c_tilt = 0.25 + 0.2625 * V
+]]>
+</artwork>
+</figure>
+for voiced frames, where V is the voice activity level between 0 and 1.
+</t>
+<t>
+The adjustment gain G serves to correct any level mismatch between the original
+and decoded signals that might arise from the noise shaping and de-emphasis.
+This gain is computed as the ratio of the prediction gain of the short-term
+analysis and synthesis filter coefficients. The prediction gain of an LPC
+synthesis filter is the square root of the output energy when the filter is
+excited by a unit-energy impulse on the input.
+An efficient way to compute the prediction gain is by first computing the
+reflection coefficients from the LPC coefficients through the step-down
+algorithm, and extracting the prediction gain from the reflection coefficients
+as
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+               K
+              ___          2  -0.5
+ predGain = ( | | 1 - (r_k)  )    ,
+              k=1
+]]>
+</artwork>
+</figure>
+where r_k is the k'th reflection coefficient.
+</t>
+
+<t>
+Initial values for the quantization gains are computed as the square-root of
+the residual energy of the LPC analysis, adjusted by the coding quality control
+parameter.
+These quantization gains are later adjusted based on the results of the
+prediction analysis.
+</t>
+</section>
+
+<section title='Prediction Analysis' anchor='pred_ana_overview_section'>
+<t>
+The prediction analysis is performed in one of two ways depending on how
+the pitch estimator classified the frame.
+The processing for voiced and unvoiced speech is described in
+<xref target='pred_ana_voiced_overview_section' /> and
+  <xref target='pred_ana_unvoiced_overview_section' />, respectively.
+  Inputs to this function include the pre-whitened signal from the
+  pitch estimator (see <xref target='pitch_estimator_overview_section'/>).
+</t>
+
+<section title='Voiced Speech' anchor='pred_ana_voiced_overview_section'>
+<t>
+  For a frame of voiced speech the pitch pulses will remain dominant in the
+  pre-whitened input signal.
+  Further whitening is desirable as it leads to higher quality at the same
+  available bitrate.
+  To achieve this, a Long-Term Prediction (LTP) analysis is carried out to
+  estimate the coefficients of a fifth-order LTP filter for each of four
+  subframes.
+  The LTP coefficients are quantized using the method described in
+  <xref target='ltp_quantizer_overview_section'/>, and the quantized LTP
+  coefficients are used to compute the LTP residual signal.
+  This LTP residual signal is the input to an LPC analysis where the LPC coefficients are
+  estimated using Burg's method <xref target="Burg"/>, such that the residual energy is minimized.
+  The estimated LPC coefficients are converted to a Line Spectral Frequency (LSF) vector
+  and quantized as described in <xref target='lsf_quantizer_overview_section'/>.
+After quantization, the quantized LSF vector is converted back to LPC
+coefficients using the full procedure in <xref target="silk_nlsfs"/>.
+By using quantized LTP coefficients and LPC coefficients derived from the
+quantized LSF coefficients, the encoder remains fully synchronized with the
+decoder.
+The quantized LPC and LTP coefficients are also used to filter the input
+signal and measure residual energy for each of the four subframes.
+</t>
+</section>
+<section title='Unvoiced Speech' anchor='pred_ana_unvoiced_overview_section'>
+<t>
+For a speech signal that has been classified as unvoiced, there is no need
+for LTP filtering, as it has already been determined that the pre-whitened
+input signal is not periodic enough within the allowed pitch period range
+for LTP analysis to be worth the cost in terms of complexity and bitrate.
+The pre-whitened input signal is therefore discarded, and instead the input
+signal is used for LPC analysis using Burg's method.
+The resulting LPC coefficients are converted to an LSF vector and quantized
+as described in the following section.
+They are then transformed back to obtain quantized LPC coefficients, which
+are then used to filter the input signal and measure residual energy for
+each of the four subframes.
+</t>
+<section title="Burg's Method">
+<t>
+The main purpose of linear prediction in SILK is to reduce the bitrate by
+minimizing the residual energy.
+At least at high bitrates, perceptual aspects are handled
+independently by the noise shaping filter.
+Burg's method is used because it provides higher prediction gain
+than the autocorrelation method and, unlike the covariance method,
+produces stable filters (assuming numerical errors don't spoil
+that). SILK's implementation of Burg's method is also computationally
+faster than the autocovariance method.
+The implementation of Burg's method differs from traditional
+implementations in two aspects.
+The first difference is that it
+operates on autocorrelations, similar to the Schur algorithm <xref target="Schur"/>, but
+with a simple update to the autocorrelations after finding each
+reflection coefficient to make the result identical to Burg's method.
+This brings down the complexity of Burg's method to near that of
+the autocorrelation method.
+The second difference is that the signal in each subframe is scaled
+by the inverse of the residual quantization step size.  Subframes with
+a small quantization step size will on average spend more bits for a
+given amount of residual energy than subframes with a large step size.
+Without scaling, Burg's method minimizes the total residual energy in
+all subframes, which doesn't necessarily minimize the total number of
+bits needed for coding the quantized residual.  The residual energy
+of the scaled subframes is a better measure for that number of
+bits.
+</t>
+</section>
+</section>
+</section>
+
+<section title='LSF Quantization' anchor='lsf_quantizer_overview_section'>
+<t>
+Unlike many other speech codecs, SILK uses variable bitrate coding
+for the LSFs.
+This improves the average rate-distortion (R-D) tradeoff and reduces outliers.
+The variable bitrate coding minimizes a linear combination of the weighted
+quantization errors and the bitrate.
+The weights for the quantization errors are the Inverse
+Harmonic Mean Weighting (IHMW) function proposed by Laroia et al.
+(see <xref target="laroia-icassp" />).
+These weights are referred to here as Laroia weights.
+</t>
+<t>
+The LSF quantizer consists of two stages.
+The first stage is an (unweighted) vector quantizer (VQ), with a
+codebook size of 32 vectors.
+The quantization errors for the codebook vector are sorted, and
+for the N best vectors a second stage quantizer is run.
+By varying the number N a tradeoff is made between R-D performance
+and computational efficiency.
+For each of the N codebook vectors the Laroia weights corresponding
+to that vector (and not to the input vector) are calculated.
+Then the residual between the input LSF vector and the codebook
+vector is scaled by the square roots of these Laroia weights.
+This scaling partially normalizes error sensitivity for the
+residual vector, so that a uniform quantizer with fixed
+step sizes can be used in the second stage without too much
+performance loss.
+And by scaling with Laroia weights determined from the first-stage
+codebook vector, the process can be reversed in the decoder.
+</t>
+<t>
+The second stage uses predictive delayed decision scalar
+quantization.
+The quantization error is weighted by Laroia weights determined
+from the LSF input vector.
+The predictor multiplies the previous quantized residual value
+by a prediction coefficient that depends on the vector index from the
+first stage VQ and on the location in the LSF vector.
+The prediction is subtracted from the LSF residual value before
+quantizing the result, and added back afterwards.
+This subtraction can be interpreted as shifting the quantization levels
+of the scalar quantizer, and as a result the quantization error of
+each value depends on the quantization decision of the previous value.
+This dependency is exploited by the delayed decision mechanism to
+search for a quantization sequency with best R-D performance
+with a Viterbi-like algorithm <xref target="Viterbi"/>.
+The quantizer processes the residual LSF vector in reverse order
+(i.e., it starts with the highest residual LSF value).
+This is done because the prediction works slightly
+better in the reverse direction.
+</t>
+<t>
+The quantization index of the first stage is entropy coded.
+The quantization sequence from the second stage is also entropy
+coded, where for each element the probability table is chosen
+depending on the vector index from the first stage and the location
+of that element in the LSF vector.
+</t>
+
+<section title='LSF Stabilization' anchor='lsf_stabilizer_overview_section'>
+<t>
+If the input is stable, finding the best candidate usually results in a
+quantized vector that is also stable. Because of the two-stage approach,
+however, it is possible that the best quantization candidate is unstable.
+The encoder applies the same stabilization procedure applied by the decoder
+ (see <xref target="silk_nlsf_stabilization"/> to ensure the LSF parameters
+ are within their valid range, increasingly sorted, and have minimum
+ distances between each other and the border values.
+</t>
+</section>
+</section>
+
+<section title='LTP Quantization' anchor='ltp_quantizer_overview_section'>
+<t>
+For voiced frames, the prediction analysis described in
+<xref target='pred_ana_voiced_overview_section' /> resulted in four sets
+(one set per subframe) of five LTP coefficients, plus four weighting matrices.
+The LTP coefficients for each subframe are quantized using entropy constrained
+vector quantization.
+A total of three vector codebooks are available for quantization, with
+different rate-distortion trade-offs. The three codebooks have 10, 20, and
+40 vectors and average rates of about 3, 4, and 5 bits per vector, respectively.
+Consequently, the first codebook has larger average quantization distortion at
+a lower rate, whereas the last codebook has smaller average quantization
+distortion at a higher rate.
+Given the weighting matrix W_ltp and LTP vector b, the weighted rate-distortion
+measure for a codebook vector cb_i with rate r_i is give by
+<figure align="center">
+<artwork align="center">
+<![CDATA[
+ RD = u * (b - cb_i)' * W_ltp * (b - cb_i) + r_i,
+]]>
+</artwork>
+</figure>
+where u is a fixed, heuristically-determined parameter balancing the distortion
+and rate.
+Which codebook gives the best performance for a given LTP vector depends on the
+weighting matrix for that LTP vector.
+For example, for a low valued W_ltp, it is advantageous to use the codebook
+with 10 vectors as it has a lower average rate.
+For a large W_ltp, on the other hand, it is often better to use the codebook
+with 40 vectors, as it is more likely to contain the best codebook vector.
+The weighting matrix W_ltp depends mostly on two aspects of the input signal.
+The first is the periodicity of the signal; the more periodic, the larger W_ltp.
+The second is the change in signal energy in the current subframe, relative to
+the signal one pitch lag earlier.
+A decaying energy leads to a larger W_ltp than an increasing energy.
+Both aspects fluctuate relatively slowly, which causes the W_ltp matrices for
+different subframes of one frame often to be similar.
+Because of this, one of the three codebooks typically gives good performance
+for all subframes, and therefore the codebook search for the subframe LTP
+vectors is constrained to only allow codebook vectors to be chosen from the
+same codebook, resulting in a rate reduction.
+</t>
+
+<t>
+To find the best codebook, each of the three vector codebooks is
+used to quantize all subframe LTP vectors and produce a combined
+weighted rate-distortion measure for each vector codebook.
+The vector codebook with the lowest combined rate-distortion
+over all subframes is chosen. The quantized LTP vectors are used
+in the noise shaping quantizer, and the index of the codebook
+plus the four indices for the four subframe codebook vectors
+are passed on to the range encoder.
+</t>
+</section>
+
+<section title='Prefilter'>
+<t>
+In the prefilter the input signal is filtered using the spectral valley
+de-emphasis filter coefficients from the noise shaping analysis
+(see <xref target='noise_shaping_analysis_overview_section'/>).
+By applying only the noise shaping analysis filter to the input signal,
+it provides the input to the noise shaping quantizer.
+</t>
+</section>
+
+<section title='Noise Shaping Quantizer'>
+<t>
+The noise shaping quantizer independently shapes the signal and coding noise
+spectra to obtain a perceptually higher quality at the same bitrate.
+</t>
+<t>
+The prefilter output signal is multiplied with a compensation gain G computed
+in the noise shaping analysis. Then the output of a synthesis shaping filter
+is added, and the output of a prediction filter is subtracted to create a
+residual signal.
+The residual signal is multiplied by the inverse quantized quantization gain
+from the noise shaping analysis, and input to a scalar quantizer.
+The quantization indices of the scalar quantizer represent a signal of pulses
+that is input to the pyramid range encoder.
+The scalar quantizer also outputs a quantization signal, which is multiplied
+by the quantized quantization gain from the noise shaping analysis to create
+an excitation signal.
+The output of the prediction filter is added to the excitation signal to form
+the quantized output signal y(n).
+The quantized output signal y(n) is input to the synthesis shaping and
+prediction filters.
+</t>
+<t>
+Optionally the noise shaping quantizer operates in a delayed decision
+mode.
+In this mode it uses a Viterbi algorithm to keep track of
+multiple rounding choices in the quantizer and select the best
+one after a delay of 32 samples.  This improves the rate/distortion
+performance of the quantizer.
+</t>
+</section>
+
+<section title='Constant Bitrate Mode'>
+<t>
+  SILK was designed to run in Variable Bitrate (VBR) mode.  However
+  the reference implementation also has a Constant Bitrate (CBR) mode
+  for SILK.  In CBR mode SILK will attempt to encode each packet with
+  no more than the allowed number of bits.  The Opus wrapper code
+  then pads the bitstream if any unused bits are left in SILK mode, or
+  encodes the high band with the remaining number of bits in Hybrid mode.
+  The number of payload bits is adjusted by changing
+  the quantization gains and the rate/distortion tradeoff in the noise
+  shaping quantizer, in an iterative loop
+  around the noise shaping quantizer and entropy coding.
+  Compared to the SILK VBR mode, the CBR mode has lower
+  audio quality at a given average bitrate, and also has higher
+  computational complexity.
+</t>
+</section>
+
+</section>
+
+</section>
+
+
+<section title="CELT Encoder">
+<t>
+Most of the aspects of the CELT encoder can be directly derived from the description
+of the decoder. For example, the filters and rotations in the encoder are simply the
+inverse of the operation performed by the decoder. Similarly, the quantizers generally
+optimize for the mean square error (because noise shaping is part of the bit-stream itself),
+so no special search is required. For this reason, only the less straightforward aspects of the
+encoder are described here.
+</t>
+
+<section anchor="pitch-prefilter" title="Pitch Prefilter">
+<t>The pitch prefilter is applied after the pre-emphasis. It is applied
+in such a way as to be the inverse of the decoder's post-filter. The main non-obvious aspect of the
+prefilter is the selection of the pitch period. The pitch search should be optimized for the
+following criteria:
+<list style="symbols">
+<t>continuity: it is important that the pitch period
+does not change abruptly between frames; and</t>
+<t>avoidance of pitch multiples: when the period used is a multiple of the real period
+(lower frequency fundamental), the post-filter loses most of its ability to reduce noise</t>
+</list>
+</t>
+</section>
+
+<section anchor="normalization" title="Bands and Normalization">
+<t>
+The MDCT output is divided into bands that are designed to match the ear's critical
+bands for the smallest (2.5&nbsp;ms) frame size. The larger frame sizes use integer
+multiples of the 2.5&nbsp;ms layout. For each band, the encoder
+computes the energy that will later be encoded. Each band is then normalized by the
+square root of the <spanx style="strong">unquantized</spanx> energy, such that each band now forms a unit vector X.
+The energy and the normalization are computed by compute_band_energies()
+and normalise_bands() (bands.c), respectively.
+</t>
+</section>
+
+<section anchor="energy-quantization" title="Energy Envelope Quantization">
+
+<t>
+Energy quantization (both coarse and fine) can be easily understood from the decoding process.
+For all useful bitrates, the coarse quantizer always chooses the quantized log energy value that
+minimizes the error for each band. Only at very low rate does the encoder allow larger errors to
+minimize the rate and avoid using more bits than are available. When the
+available CPU requirements allow it, it is best to try encoding the coarse energy both with and without
+inter-frame prediction such that the best prediction mode can be selected. The optimal mode depends on
+the coding rate, the available bitrate, and the current rate of packet loss.
+</t>
+
+<t>The fine energy quantizer always chooses the quantized log energy value that
+minimizes the error for each band because the rate of the fine quantization depends only
+on the bit allocation and not on the values that are coded.
+</t>
+</section> <!-- Energy quant -->
+
+<section title="Bit Allocation">
+<t>The encoder must use exactly the same bit allocation process as used by the decoder
+and described in <xref target="allocation"/>. The three mechanisms that can be used by the
+encoder to adjust the bitrate on a frame-by-frame basis are band boost, allocation trim,
+and band skipping.
+</t>
+
+<section title="Band Boost">
+<t>The reference encoder makes a decision to boost a band when the energy of that band is significantly
+higher than that of the neighboring bands. Let E_j be the log-energy of band j, we define
+<list>
+<t>D_j = 2*E_j - E_j-1 - E_j+1 </t>
+</list>
+
+The allocation of band j is boosted once if D_j &gt; t1 and twice if D_j &gt; t2. For LM&gt;=1, t1=2 and t2=4,
+while for LM&lt;1, t1=3 and t2=5.
+</t>
+
+</section>
+
+<section title="Allocation Trim">
+<t>The allocation trim is a value between 0 and 10 (inclusively) that controls the allocation
+balance between the low and high frequencies. The encoder starts with a safe "default" of 5
+and deviates from that default in two different ways. First the trim can deviate by +/- 2
+depending on the spectral tilt of the input signal. For signals with more low frequencies, the
+trim is increased by up to 2, while for signals with more high frequencies, the trim is
+decreased by up to 2.
+For stereo inputs, the trim value can
+be decreased by up to 4 when the inter-channel correlation at low frequency (first 8 bands)
+is high. </t>
+</section>
+
+<section title="Band Skipping">
+<t>The encoder uses band skipping to ensure that the shape of the bands is only coded
+if there is at least 1/2 bit per sample available for the PVQ. If not, then no bit is allocated
+and folding is used instead. To ensure continuity in the allocation, some amount of hysteresis is
+added to the process, such that a band that received PVQ bits in the previous frame only needs 7/16
+bit/sample to be coded for the current frame, while a band that did not receive PVQ bits in the
+previous frames needs at least 9/16 bit/sample to be coded.</t>
+</section>
+
+</section>
+
+<section title="Stereo Decisions">
+<t>Because CELT applies mid-side stereo coupling in the normalized domain, it does not suffer from
+important stereo image problems even when the two channels are completely uncorrelated. For this reason
+it is always safe to use stereo coupling on any audio frame. That being said, there are some frames
+for which dual (independent) stereo is still more efficient. This decision is made by comparing the estimated
+entropy with and without coupling over the first 13 bands, taking into account the fact that all bands with
+more than two MDCT bins require one extra degree of freedom when coded in mid-side. Let L1_ms and L1_lr
+be the L1-norm of the mid-side vector and the L1-norm of the left-right vector, respectively. The decision
+to use mid-side is made if and only if
+<figure align="center">
+<artwork align="center"><![CDATA[
+ L1_ms          L1_lr
+--------    <   -----
+bins + E        bins
+]]></artwork>
+</figure>
+where bins is the number of MDCT bins in the first 13 bands and E is the number of extra degrees of
+freedom for mid-side coding. For LM>1, E=13, otherwise E=5.
+</t>
+
+<t>The reference encoder decides on the intensity stereo threshold based on the bitrate alone. After
+taking into account the frame size by subtracting 80 bits per frame for coarse energy, the first
+band using intensity coding is as follows:
+</t>
+
+<texttable anchor="intensity-thresholds"
+ title="Thresholds for Intensity Stereo">
+<ttcol align='center'>bitrate (kb/s)</ttcol>
+<ttcol align='center'>start band</ttcol>
+<c>&lt;35</c>      <c>8</c>
+<c>35-50</c>      <c>12</c>
+<c>50-68</c>      <c>16</c>
+<c>84-84</c>      <c>18</c>
+<c>84-102</c>     <c>19</c>
+<c>102-130</c>     <c>20</c>
+<c>&gt;130</c>     <c>disabled</c>
+</texttable>
+
+
+</section>
+
+<section title="Time-Frequency Decision">
+<t>
+The choice of time-frequency resolution used in <xref target="tf-change"></xref> is based on
+R-D optimization. The distortion is the L1-norm (sum of absolute values) of each band
+after each TF resolution under consideration. The L1 norm is used because it represents the entropy
+for a Laplacian source. The number of bits required to code a change in TF resolution between
+two bands is higher than the cost of having those two bands use the same resolution, which is
+what requires the R-D optimization. The optimal decision is computed using the Viterbi algorithm.
+See tf_analysis() in celt/celt.c.
+</t>
+</section>
+
+<section title="Spreading Values Decision">
+<t>
+The choice of the spreading value in <xref target="spread values"></xref> has an
+impact on the nature of the coding noise introduced by CELT. The larger the f_r value, the
+lower the impact of the rotation, and the more tonal the coding noise. The
+more tonal the signal, the more tonal the noise should be, so the CELT encoder determines
+the optimal value for f_r by estimating how tonal the signal is. The tonality estimate
+is based on discrete pdf (4-bin histogram) of each band. Bands that have a large number of small
+values are considered more tonal and a decision is made by combining all bands with more than
+8 samples. See spreading_decision() in celt/bands.c.
+</t>
+</section>
+
+<section anchor="pvq" title="Spherical Vector Quantization">
+<t>CELT uses a Pyramid Vector Quantization (PVQ) <xref target="PVQ"></xref>
+codebook for quantizing the details of the spectrum in each band that have not
+been predicted by the pitch predictor. The PVQ codebook consists of all sums
+of K signed pulses in a vector of N samples, where two pulses at the same position
+are required to have the same sign. Thus the codebook includes
+all integer codevectors y of N dimensions that satisfy sum(abs(y(j))) = K.
+</t>
+
+<t>
+In bands where there are sufficient bits allocated PVQ is used to encode
+the unit vector that results from the normalization in
+<xref target="normalization"></xref> directly. Given a PVQ codevector y,
+the unit vector X is obtained as X = y/||y||, where ||.|| denotes the
+L2 norm.
+</t>
+
+
+<section anchor="pvq-search" title="PVQ Search">
+
+<t>
+The search for the best codevector y is performed by alg_quant()
+(vq.c). There are several possible approaches to the
+search, with a trade-off between quality and complexity. The method used in the reference
+implementation computes an initial codeword y1 by projecting the normalized spectrum
+X onto the codebook pyramid of K-1 pulses:
+</t>
+<t>
+y0 = truncate_towards_zero( (K-1) * X / sum(abs(X)))
+</t>
+
+<t>
+Depending on N, K and the input data, the initial codeword y0 may contain from
+0 to K-1 non-zero values. All the remaining pulses, with the exception of the last one,
+are found iteratively with a greedy search that minimizes the normalized correlation
+between y and X:
+<figure align="center">
+<artwork align="center"><![CDATA[
+      T
+J = -X * y / ||y||
+]]></artwork>
+</figure>
+</t>
+
+<t>
+The search described above is considered to be a good trade-off between quality
+and computational cost. However, there are other possible ways to search the PVQ
+codebook and the implementers MAY use any other search methods. See alg_quant() in celt/vq.c.
+</t>
+</section>
+
+<section anchor="cwrs-encoder" title="PVQ Encoding">
+
+<t>
+The vector to encode, X, is converted into an index i such that
+ 0&nbsp;&lt;=&nbsp;i&nbsp;&lt;&nbsp;V(N,K) as follows.
+Let i&nbsp;=&nbsp;0 and k&nbsp;=&nbsp;0.
+Then for j&nbsp;=&nbsp;(N&nbsp;-&nbsp;1) down to 0, inclusive, do:
+<list style="numbers">
+<t>
+If k&nbsp;>&nbsp;0, set
+ i&nbsp;=&nbsp;i&nbsp;+&nbsp;(V(N-j-1,k-1)&nbsp;+&nbsp;V(N-j,k-1))/2.
+</t>
+<t>Set k&nbsp;=&nbsp;k&nbsp;+&nbsp;abs(X[j]).</t>
+<t>
+If X[j]&nbsp;&lt;&nbsp;0, set
+ i&nbsp;=&nbsp;i&nbsp;+&nbsp;(V(N-j-1,k)&nbsp;+&nbsp;V(N-j,k))/2.
+</t>
+</list>
+</t>
+
+<t>
+The index i is then encoded using the procedure in
+ <xref target="encoding-ints"/> with ft&nbsp;=&nbsp;V(N,K).
+</t>
+
+</section>
+
+</section>
+
+
+
+
+
+</section>
+
+</section>
+
+
+<section anchor="conformance" title="Conformance">
+
+<t>
+It is our intention to allow the greatest possible choice of freedom in
+implementing the specification. For this reason, outside of the exceptions
+noted in this section, conformance is defined through the reference
+implementation of the decoder provided in <xref target="ref-implementation"/>.
+Although this document includes an English description of the codec, should
+the description contradict the source code of the reference implementation,
+the latter shall take precedence.
+</t>
+
+<t>
+Compliance with this specification means that in addition to following the normative keywords in this document,
+ a decoder's output MUST also be
+ within the thresholds specified by the opus_compare.c tool (included
+ with the code) when compared to the reference implementation for each of the
+ test vectors provided (see <xref target="test-vectors"></xref>) and for each output
+ sampling rate and channel count supported. In addition, a compliant
+ decoder implementation MUST have the same final range decoder state as that of the
+ reference decoder. It is therefore RECOMMENDED that the
+ decoder implement the same functional behavior as the reference.
+
+ A decoder implementation is not required to support all output sampling
+ rates or all output channel counts.
+</t>
+
+<section title="Testing">
+<t>
+Using the reference code provided in <xref target="ref-implementation"></xref>,
+a test vector can be decoded with
+<list>
+<t>opus_demo -d &lt;rate&gt; &lt;channels&gt; testvectorX.bit testX.out</t>
+</list>
+where &lt;rate&gt; is the sampling rate and can be 8000, 12000, 16000, 24000, or 48000, and
+&lt;channels&gt; is 1 for mono or 2 for stereo.
+</t>
+
+<t>
+If the range decoder state is incorrect for one of the frames, the decoder will exit with
+"Error: Range coder state mismatch between encoder and decoder". If the decoder succeeds, then
+the output can be compared with the "reference" output with
+<list>
+<t>opus_compare -s -r &lt;rate&gt; testvectorX.dec testX.out</t>
+</list>
+for stereo or
+<list>
+<t>opus_compare -r &lt;rate&gt; testvectorX.dec testX.out</t>
+</list>
+for mono.
+</t>
+
+<t>In addition to indicating whether the test vector comparison passes, the opus_compare tool
+outputs an "Opus quality metric" that indicates how well the tested decoder matches the
+reference implementation. A quality of 0 corresponds to the passing threshold, while
+a quality of 100 is the highest possible value and means that the output of the tested decoder is identical to the reference
+implementation. The passing threshold (quality 0) was calibrated in such a way that it corresponds to
+additive white noise with a 48 dB SNR (similar to what can be obtained on a cassette deck).
+It is still possible for an implementation to sound very good with such a low quality measure
+(e.g. if the deviation is due to inaudible phase distortion), but unless this is verified by
+listening tests, it is RECOMMENDED that implementations achieve a quality above 90 for 48&nbsp;kHz
+decoding. For other sampling rates, it is normal for the quality metric to be lower
+(typically as low as 50 even for a good implementation) because of harmless mismatch with
+the delay and phase of the internal sampling rate conversion.
+</t>
+
+<t>
+On POSIX environments, the run_vectors.sh script can be used to verify all test
+vectors. This can be done with
+<list>
+<t>run_vectors.sh &lt;exec path&gt; &lt;vector path&gt; &lt;rate&gt;</t>
+</list>
+where &lt;exec path&gt; is the directory where the opus_demo and opus_compare executables
+are built and &lt;vector path&gt; is the directory containing the test vectors.
+</t>
+</section>
+
+<section anchor="opus-custom" title="Opus Custom">
+<t>
+Opus Custom is an OPTIONAL part of the specification that is defined to
+handle special sample rates and frame rates that are not supported by the
+main Opus specification. Use of Opus Custom is discouraged for all but very
+special applications for which a frame size different from 2.5, 5, 10, or 20&nbsp;ms is
+needed (for either complexity or latency reasons). Because Opus Custom is
+optional, streams encoded using Opus Custom cannot be expected to be decodable by all Opus
+implementations. Also, because no in-band mechanism exists for specifying the sampling
+rate and frame size of Opus Custom streams, out-of-band signaling is required.
+In Opus Custom operation, only the CELT layer is available, using the opus_custom_* function
+calls in opus_custom.h.
+</t>
+</section>
+
+</section>
+
+<section anchor="security" title="Security Considerations">
+
+<t>
+Implementations of the Opus codec need to take appropriate security considerations
+into account, as outlined in <xref target="DOS"/>.
+It is extremely important for the decoder to be robust against malicious
+payloads.
+Malicious payloads must not cause the decoder to overrun its allocated memory
+ or to take an excessive amount of resources to decode.
+Although problems
+in encoders are typically rarer, the same applies to the encoder. Malicious
+audio streams must not cause the encoder to misbehave because this would
+allow an attacker to attack transcoding gateways.
+</t>
+<t>
+The reference implementation contains no known buffer overflow or cases where
+ a specially crafted packet or audio segment could cause a significant increase
+ in CPU load.
+However, on certain CPU architectures where denormalized floating-point
+ operations are much slower than normal floating-point operations, it is
+ possible for some audio content (e.g., silence or near-silence) to cause an
+ increase in CPU load.
+Denormals can be introduced by reordering operations in the compiler and depend
+ on the target architecture, so it is difficult to guarantee that an implementation
+ avoids them.
+For architectures on which denormals are problematic, adding very small
+ floating-point offsets to the affected signals to prevent significant numbers
+ of denormalized operations is RECOMMENDED.
+Alternatively, it is often possible to configure the hardware to treat
+ denormals as zero (DAZ).
+No such issue exists for the fixed-point reference implementation.
+</t>
+<t>The reference implementation was validated in the following conditions:
+<list style="numbers">
+<t>
+Sending the decoder valid packets generated by the reference encoder and
+ verifying that the decoder's final range coder state matches that of the
+ encoder.
+</t>
+<t>
+Sending the decoder packets generated by the reference encoder and then
+ subjected to random corruption.
+</t>
+<t>Sending the decoder random packets.</t>
+<t>
+Sending the decoder packets generated by a version of the reference encoder
+ modified to make random coding decisions (internal fuzzing), including mode
+ switching, and verifying that the range coder final states match.
+</t>
+</list>
+In all of the conditions above, both the encoder and the decoder were run
+ inside the <xref target="Valgrind">Valgrind</xref> memory
+ debugger, which tracks reads and writes to invalid memory regions as well as
+ the use of uninitialized memory.
+There were no errors reported on any of the tested conditions.
+</t>
+</section>
+
+
+<section title="IANA Considerations">
+<t>
+This document has no actions for IANA.
+</t>
+</section>
+
+<section anchor="Acknowledgements" title="Acknowledgements">
+<t>
+Thanks to all other developers, including Raymond Chen, Soeren Skak Jensen, Gregory Maxwell,
+Christopher Montgomery, and Karsten Vandborg Soerensen. We would also
+like to thank Igor Dyakonov, Jan Skoglund, and Christian Hoene for their help with subjective testing of the
+Opus codec. Thanks to Ralph Giles, John Ridges, Ben Schwartz, Keith Yan, Christian Hoene, Kat Walsh, and many others on the Opus and CELT mailing lists
+for their bug reports and feedback.
+</t>
+</section>
+
+<section title="Copying Conditions">
+<t>The authors agree to grant third parties the irrevocable right to copy, use and distribute
+the work (excluding Code Components available under the simplified BSD license), with or
+without modification, in any medium, without royalty, provided that, unless separate
+permission is granted, redistributed modified works do not contain misleading author, version,
+name of work, or endorsement information.</t>
+</section>
+
+</middle>
+
+<back>
+
+<references title="Normative References">
+
+<reference anchor="rfc2119">
+<front>
+<title>Key words for use in RFCs to Indicate Requirement Levels </title>
+<author initials="S." surname="Bradner" fullname="Scott Bradner"></author>
+</front>
+<seriesInfo name="RFC" value="2119" />
+</reference>
+
+</references>
+
+<references title="Informative References">
+
+<reference anchor='requirements'>
+<front>
+<title>Requirements for an Internet Audio Codec</title>
+<author initials='J.-M.' surname='Valin' fullname='J.-M. Valin'>
+<organization /></author>
+<author initials='K.' surname='Vos' fullname='K. Vos'>
+<organization /></author>
+<author>
+<organization>IETF</organization></author>
+<date year='2011' month='August' />
+<abstract>
+<t>This document provides specific requirements for an Internet audio
+   codec.  These requirements address quality, sample rate, bitrate,
+   and packet-loss robustness, as well as other desirable properties.
+</t></abstract></front>
+<seriesInfo name='RFC' value='6366' />
+<format type='TXT' target='http://tools.ietf.org/rfc/rfc6366.txt' />
+</reference>
+
+<?rfc include="http://xml.resource.org/public/rfc/bibxml/reference.RFC.3550.xml"?>
+<?rfc include="http://xml.resource.org/public/rfc/bibxml/reference.RFC.3533.xml"?>
+
+<reference anchor='SILK' target='http://developer.skype.com/silk'>
+<front>
+<title>SILK Speech Codec</title>
+<author initials='K.' surname='Vos' fullname='K. Vos'>
+<organization /></author>
+<author initials='S.' surname='Jensen' fullname='S. Jensen'>
+<organization /></author>
+<author initials='K.' surname='Soerensen' fullname='K. Soerensen'>
+<organization /></author>
+<date year='2010' month='March' />
+<abstract>
+<t></t>
+</abstract></front>
+<seriesInfo name='Internet-Draft' value='draft-vos-silk-01' />
+<format type='TXT' target='http://tools.ietf.org/html/draft-vos-silk-01' />
+</reference>
+
+<reference anchor="laroia-icassp">
+<front>
+<title abbrev="Robust and Efficient Quantization of Speech LSP">
+Robust and Efficient Quantization of Speech LSP Parameters Using Structured Vector Quantization
+</title>
+<author initials="R.L." surname="Laroia" fullname="R.">
+<organization/>
+</author>
+<author initials="N.P." surname="Phamdo" fullname="N.">
+<organization/>
+</author>
+<author initials="N.F." surname="Farvardin" fullname="N.">
+<organization/>
+</author>
+</front>
+<seriesInfo name="ICASSP-1991, Proc. IEEE Int. Conf. Acoust., Speech, Signal Processing, pp. 641-644, October" value="1991"/>
+</reference>
+
+<reference anchor='CELT' target='http://celt-codec.org/'>
+<front>
+<title>Constrained-Energy Lapped Transform (CELT) Codec</title>
+<author initials='J-M.' surname='Valin' fullname='J-M. Valin'>
+<organization /></author>
+<author initials='T&#x2E;B.' surname='Terriberry' fullname='Timothy B. Terriberry'>
+<organization /></author>
+<author initials='G.' surname='Maxwell' fullname='G. Maxwell'>
+<organization /></author>
+<author initials='C.' surname='Montgomery' fullname='C. Montgomery'>
+<organization /></author>
+<date year='2010' month='July' />
+<abstract>
+<t></t>
+</abstract></front>
+<seriesInfo name='Internet-Draft' value='draft-valin-celt-codec-02' />
+<format type='TXT' target='http://tools.ietf.org/html/draft-valin-celt-codec-02' />
+</reference>
+
+<reference anchor='SRTP-VBR'>
+<front>
+<title>Guidelines for the use of Variable Bit Rate Audio with Secure RTP</title>
+<author initials='C.' surname='Perkins' fullname='K. Vos'>
+<organization /></author>
+<author initials='J.M.' surname='Valin' fullname='J.M. Valin'>
+<organization /></author>
+<date year='2011' month='July' />
+<abstract>
+<t></t>
+</abstract></front>
+<seriesInfo name='RFC' value='6562' />
+<format type='TXT' target='http://tools.ietf.org/html/rfc6562' />
+</reference>
+
+<reference anchor='DOS'>
+<front>
+<title>Internet Denial-of-Service Considerations</title>
+<author initials='M.' surname='Handley' fullname='M. Handley'>
+<organization /></author>
+<author initials='E.' surname='Rescorla' fullname='E. Rescorla'>
+<organization /></author>
+<author>
+<organization>IAB</organization></author>
+<date year='2006' month='December' />
+<abstract>
+<t>This document provides an overview of possible avenues for denial-of-service (DoS) attack on Internet systems.  The aim is to encourage protocol designers and network engineers towards designs that are more robust.  We discuss partial solutions that reduce the effectiveness of attacks, and how some solutions might inadvertently open up alternative vulnerabilities.  This memo provides information for the Internet community.</t></abstract></front>
+<seriesInfo name='RFC' value='4732' />
+<format type='TXT' octets='91844' target='ftp://ftp.isi.edu/in-notes/rfc4732.txt' />
+</reference>
+
+<reference anchor="Martin79">
+<front>
+<title>Range encoding: An algorithm for removing redundancy from a digitised message</title>
+<author initials="G.N.N." surname="Martin" fullname="G. Nigel N. Martin"><organization/></author>
+<date year="1979" />
+</front>
+<seriesInfo name="Proc. Institution of Electronic and Radio Engineers International Conference on Video and Data Recording" value="" />
+</reference>
+
+<reference anchor="coding-thesis">
+<front>
+<title>Source coding algorithms for fast data compression</title>
+<author initials="R." surname="Pasco" fullname=""><organization/></author>
+<date month="May" year="1976" />
+</front>
+<seriesInfo name="Ph.D. thesis" value="Dept. of Electrical Engineering, Stanford University" />
+</reference>
+
+<reference anchor="PVQ">
+<front>
+<title>A Pyramid Vector Quantizer</title>
+<author initials="T." surname="Fischer" fullname=""><organization/></author>
+<date month="July" year="1986" />
+</front>
+<seriesInfo name="IEEE Trans. on Information Theory, Vol. 32" value="pp. 568-583" />
+</reference>
+
+<reference anchor="Kabal86">
+<front>
+<title>The Computation of Line Spectral Frequencies Using Chebyshev Polynomials</title>
+<author initials="P." surname="Kabal" fullname="P. Kabal"><organization/></author>
+<author initials="R." surname="Ramachandran" fullname="R. P. Ramachandran"><organization/></author>
+<date month="December" year="1986" />
+</front>
+<seriesInfo name="IEEE Trans. Acoustics, Speech, Signal Processing, vol. 34, no. 6" value="pp. 1419-1426" />
+</reference>
+
+
+<reference anchor="Valgrind" target="http://valgrind.org/">
+<front>
+<title>Valgrind website</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Google-NetEQ" target="http://code.google.com/p/webrtc/source/browse/trunk/src/modules/audio_coding/NetEQ/main/source/?r=583">
+<front>
+<title>Google NetEQ code</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Google-WebRTC" target="http://code.google.com/p/webrtc/">
+<front>
+<title>Google WebRTC code</title>
+<author></author>
+</front>
+</reference>
+
+
+<reference anchor="Opus-git" target="git://git.xiph.org/opus.git">
+<front>
+<title>Opus Git Repository</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Opus-website" target="http://opus-codec.org/">
+<front>
+<title>Opus website</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Vorbis-website" target="http://xiph.org/vorbis/">
+<front>
+<title>Vorbis website</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Matroska-website" target="http://matroska.org/">
+<front>
+<title>Matroska website</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Vectors-website" target="http://opus-codec.org/testvectors/">
+<front>
+<title>Opus Testvectors (webside)</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="Vectors-proc" target="http://www.ietf.org/proceedings/83/slides/slides-83-codec-0.gz">
+<front>
+<title>Opus Testvectors (proceedings)</title>
+<author></author>
+</front>
+</reference>
+
+<reference anchor="line-spectral-pairs" target="http://en.wikipedia.org/wiki/Line_spectral_pairs">
+<front>
+<title>Line Spectral Pairs</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="range-coding" target="http://en.wikipedia.org/wiki/Range_coding">
+<front>
+<title>Range Coding</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="Hadamard" target="http://en.wikipedia.org/wiki/Hadamard_transform">
+<front>
+<title>Hadamard Transform</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="Viterbi" target="http://en.wikipedia.org/wiki/Viterbi_algorithm">
+<front>
+<title>Viterbi Algorithm</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="Whitening" target="http://en.wikipedia.org/wiki/White_noise">
+<front>
+<title>White Noise</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="LPC" target="http://en.wikipedia.org/wiki/Linear_prediction">
+<front>
+<title>Linear Prediction</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="MDCT" target="http://en.wikipedia.org/wiki/Modified_discrete_cosine_transform">
+<front>
+<title>Modified Discrete Cosine Transform</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="FFT" target="http://en.wikipedia.org/wiki/Fast_Fourier_transform">
+<front>
+<title>Fast Fourier Transform</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+<reference anchor="z-transform" target="http://en.wikipedia.org/wiki/Z-transform">
+<front>
+<title>Z-transform</title>
+<author><organization>Wikipedia</organization></author>
+</front>
+</reference>
+
+
+<reference anchor="Burg">
+<front>
+<title>Maximum Entropy Spectral Analysis</title>
+<author initials="JP." surname="Burg" fullname="J.P. Burg"><organization/></author>
+</front>
+</reference>
+
+<reference anchor="Schur">
+<front>
+<title>A fixed point computation of partial correlation coefficients</title>
+<author initials="J." surname="Le Roux" fullname="J. Le Roux"><organization/></author>
+<author initials="C." surname="Gueguen" fullname="C. Gueguen"><organization/></author>
+</front>
+<seriesInfo name="ICASSP-1977, Proc. IEEE Int. Conf. Acoust., Speech, Signal Processing, pp. 257-259, October" value="1977"/>
+</reference>
+
+<reference anchor="Princen86">
+<front>
+<title>Analysis/synthesis filter bank design based on time domain aliasing cancellation</title>
+<author initials="J." surname="Princen" fullname="John P. Princen"><organization/></author>
+<author initials="A." surname="Bradley" fullname="Alan B. Bradley"><organization/></author>
+</front>
+<seriesInfo name="IEEE Trans. Acoust. Speech Sig. Proc. ASSP-34 (5), 1153-1161" value="1986"/>
+</reference>
+
+<reference anchor="Valin2010">
+<front>
+<title>A High-Quality Speech and Audio Codec With Less Than 10 ms delay</title>
+<author initials="JM" surname="Valin" fullname="Jean-Marc Valin"><organization/>
+</author>
+<author initials="T. B." surname="Terriberry" fullname="Timothy Terriberry"><organization/></author>
+<author initials="C." surname="Montgomery" fullname="Christopher Montgomery"><organization/></author>
+<author initials="G." surname="Maxwell" fullname="Gregory Maxwell"><organization/></author>
+</front>
+<seriesInfo name="IEEE Trans. on Audio, Speech and Language Processing, Vol. 18, No. 1, pp. 58-67" value="2010" />
+</reference>
+
+
+<reference anchor="Zwicker61">
+<front>
+<title>Subdivision of the audible frequency range into critical bands</title>
+<author initials="E." surname="Zwicker" fullname="E. Zwicker"><organization/></author>
+<date month="February" year="1961" />
+</front>
+<seriesInfo name="The Journal of the Acoustical Society of America, Vol. 33, No 2" value="p. 248" />
+</reference>
+
+
+</references>
+
+<section anchor="ref-implementation" title="Reference Implementation">
+
+<t>This appendix contains the complete source code for the
+reference implementation of the Opus codec written in C. By default,
+this implementation relies on floating-point arithmetic, but it can be
+compiled to use only fixed-point arithmetic by defining the FIXED_POINT
+macro. Information on building and using the reference implementation is
+available in the README file.
+</t>
+
+<t>The implementation can be compiled with either a C89 or a C99
+compiler. It is reasonably optimized for most platforms such that
+only architecture-specific optimizations are likely to be useful.
+The FFT <xref target="FFT"/> used is a slightly modified version of the KISS-FFT library,
+but it is easy to substitute any other FFT library.
+</t>
+
+<t>
+While the reference implementation does not rely on any
+<spanx style="emph">undefined behavior</spanx> as defined by C89 or C99,
+it relies on common <spanx style="emph">implementation-defined behavior</spanx>
+for two's complement architectures:
+<list style="symbols">
+<t>Right shifts of negative values are consistent with two's complement arithmetic, so that a>>b is equivalent to floor(a/(2**b)),</t>
+<t>For conversion to a signed integer of N bits, the value is reduced modulo 2**N to be within range of the type,</t>
+<t>The result of integer division of a negative value is truncated towards zero, and</t>
+<t>The compiler provides a 64-bit integer type (a C99 requirement which is supported by most C89 compilers).</t>
+</list>
+</t>
+
+<t>
+In its current form, the reference implementation also requires the following
+architectural characteristics to obtain acceptable performance:
+<list style="symbols">
+<t>Two's complement arithmetic,</t>
+<t>At least a 16 bit by 16 bit integer multiplier (32-bit result), and</t>
+<t>At least a 32-bit adder/accumulator.</t>
+</list>
+</t>
+
+
+<section title="Extracting the source">
+<t>
+The complete source code can be extracted from this draft, by running the
+following command line:
+
+<list style="symbols">
+<t><![CDATA[
+cat draft-ietf-codec-opus.txt | grep '^\ \ \ ###' | sed -e 's/...###//' | base64 -d > opus_source.tar.gz
+]]></t>
+<t>
+tar xzvf opus_source.tar.gz
+</t>
+<t>cd opus_source</t>
+<t>make</t>
+</list>
+On systems where the provided Makefile does not work, the following command line may be used to compile
+the source code:
+<list style="symbols">
+<t><![CDATA[
+cc -O2 -g -o opus_demo src/opus_demo.c `cat *.mk | grep -v fixed | sed -e 's/.*=//' -e 's/\\\\//'` -DOPUS_BUILD -Iinclude -Icelt -Isilk -Isilk/float -DUSE_ALLOCA -Drestrict= -lm
+]]></t></list>
+</t>
+
+<t>
+On systems where the base64 utility is not present, the following commands can be used instead:
+<list style="symbols">
+<t><![CDATA[
+cat draft-ietf-codec-opus.txt | grep '^\ \ \ ###' | sed -e 's/...###//' > opus.b64
+]]></t>
+<t>openssl base64 -d -in opus.b64 > opus_source.tar.gz</t>
+</list>
+
+</t>
+</section>
+
+<section title="Up-to-date Implementation">
+<t>
+As of the time of publication of this memo, an up-to-date implementation conforming to
+this standard is available in a
+ <xref target='Opus-git'>Git repository</xref>.
+Releases and other resources are available at
+ <xref target='Opus-website'/>. However, although that implementation is expected to
+ remain conformant with the standard, it is the code in this document that shall
+ remain normative.
+</t>
+</section>
+
+<section title="Base64-encoded Source Code">
+<t>
+<?rfc include="opus_source.base64"?>
+</t>
+</section>
+
+<section anchor="test-vectors" title="Test Vectors">
+<t>
+Because of size constraints, the Opus test vectors are not distributed in this
+draft. They are available in the proceedings of the 83th IETF meeting (Paris) <xref target="Vectors-proc"/> and from the Opus codec website at
+<xref target="Vectors-website"/>. These test vectors were created specifically to exercise
+all aspects of the decoder and therefore the audio quality of the decoded output is
+significantly lower than what Opus can achieve in normal operation.
+</t>
+
+<t>
+The SHA1 hash of the files in the test vector package are
+<?rfc include="testvectors_sha1"?>
+</t>
+
+</section>
+
+</section>
+
+<section anchor="self-delimiting-framing" title="Self-Delimiting Framing">
+<t>
+To use the internal framing described in <xref target="modes"/>, the decoder
+ must know the total length of the Opus packet, in bytes.
+This section describes a simple variation of that framing which can be used
+ when the total length of the packet is not known.
+Nothing in the encoding of the packet itself allows a decoder to distinguish
+ between the regular, undelimited framing and the self-delimiting framing
+ described in this appendix.
+Which one is used and where must be established by context at the transport
+ layer.
+It is RECOMMENDED that a transport layer choose exactly one framing scheme,
+ rather than allowing an encoder to signal which one it wants to use.
+</t>
+
+<t>
+For example, although a regular Opus stream does not support more than two
+ channels, a multi-channel Opus stream may be formed from several one- and
+ two-channel streams.
+To pack an Opus packet from each of these streams together in a single packet
+ at the transport layer, one could use the self-delimiting framing for all but
+ the last stream, and then the regular, undelimited framing for the last one.
+Reverting to the undelimited framing for the last stream saves overhead
+ (because the total size of the transport-layer packet will still be known),
+ and ensures that a "multi-channel" stream which only has a single Opus stream
+ uses the same framing as a regular Opus stream does.
+This avoids the need for signaling to distinguish these two cases.
+</t>
+
+<t>
+The self-delimiting framing is identical to the regular, undelimited framing
+ from <xref target="modes"/>, except that each Opus packet contains one extra
+ length field, encoded using the same one- or two-byte scheme from
+ <xref target="frame-length-coding"/>.
+This extra length immediately precedes the compressed data of the first Opus
+ frame in the packet, and is interpreted in the various modes as follows:
+<list style="symbols">
+<t>
+Code&nbsp;0 packets: It is the length of the single Opus frame (see
+ <xref target="sd_code0_packet"/>).
+</t>
+<t>
+Code&nbsp;1 packets: It is the length used for both of the Opus frames (see
+ <xref target="sd_code1_packet"/>).
+</t>
+<t>
+Code&nbsp;2 packets: It is the length of the second Opus frame (see
+ <xref target="sd_code2_packet"/>).</t>
+<t>
+CBR Code&nbsp;3 packets: It is the length used for all of the Opus frames (see
+ <xref target="sd_code3cbr_packet"/>).
+</t>
+<t>VBR Code&nbsp;3 packets: It is the length of the last Opus frame (see
+ <xref target="sd_code3vbr_packet"/>).
+</t>
+</list>
+</t>
+
+<figure anchor="sd_code0_packet" title="A Self-Delimited Code 0 Packet"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|0|0| N1 (1-2 bytes):                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
+|               Compressed frame 1 (N1 bytes)...                :
+:                                                               |
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<figure anchor="sd_code1_packet" title="A Self-Delimited Code 1 Packet"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|0|1| N1 (1-2 bytes):                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               :
+|               Compressed frame 1 (N1 bytes)...                |
+:                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                               |                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               :
+|               Compressed frame 2 (N1 bytes)...                |
+:                                               +-+-+-+-+-+-+-+-+
+|                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<figure anchor="sd_code2_packet" title="A Self-Delimited Code 2 Packet"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|1|0| N1 (1-2 bytes): N2 (1-2 bytes :               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+               :
+|               Compressed frame 1 (N1 bytes)...                |
+:                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                               |                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
+|               Compressed frame 2 (N2 bytes)...                :
+:                                                               |
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<figure anchor="sd_code3cbr_packet" title="A Self-Delimited CBR Code 3 Packet"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|1|1|0|p|     M     | Pad len (Opt) : N1 (1-2 bytes):
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 1 (N1 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 2 (N1 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                              ...                              :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame M (N1 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:                  Opus Padding (Optional)...                   |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+<figure anchor="sd_code3vbr_packet" title="A Self-Delimited VBR Code 3 Packet"
+ align="center">
+<artwork align="center"><![CDATA[
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+| config  |s|1|1|1|p|     M     | Padding length (Optional)     :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+: N1 (1-2 bytes):     ...       :     N[M-1]    |     N[M]      :
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 1 (N1 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:               Compressed frame 2 (N2 bytes)...                :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:                              ...                              :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|                                                               |
+:              Compressed frame M (N[M] bytes)...               :
+|                                                               |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+:                  Opus Padding (Optional)...                   |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+]]></artwork>
+</figure>
+
+</section>
+
+</back>
+
+</rfc>
diff --git a/doc/draft-ietf-payload-rtp-opus.xml b/doc/draft-ietf-payload-rtp-opus.xml
new file mode 100644
index 0000000..02440d9
--- /dev/null
+++ b/doc/draft-ietf-payload-rtp-opus.xml
@@ -0,0 +1,932 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE rfc SYSTEM "rfc2629.dtd" [
+<!ENTITY rfc2119 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.2119.xml'>
+<!ENTITY rfc3550 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.3550.xml'>
+<!ENTITY rfc3711 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.3711.xml'>
+<!ENTITY rfc3551 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.3551.xml'>
+<!ENTITY rfc4288 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.4288.xml'>
+<!ENTITY rfc4855 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.4855.xml'>
+<!ENTITY rfc4566 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.4566.xml'>
+<!ENTITY rfc3264 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.3264.xml'>
+<!ENTITY rfc2974 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.2974.xml'>
+<!ENTITY rfc2326 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.2326.xml'>
+<!ENTITY rfc3555 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.3555.xml'>
+<!ENTITY rfc5576 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.5576.xml'>
+<!ENTITY rfc6562 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.6562.xml'>
+<!ENTITY rfc6716 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.6716.xml'>
+<!ENTITY nbsp "&#160;">
+  ]>
+
+  <rfc category="std" ipr="trust200902" docName="draft-ietf-payload-rtp-opus-01">
+<?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?>
+
+<?rfc strict="yes" ?>
+<?rfc toc="yes" ?>
+<?rfc tocdepth="3" ?>
+<?rfc tocappendix='no' ?>
+<?rfc tocindent='yes' ?>
+<?rfc symrefs="yes" ?>
+<?rfc sortrefs="yes" ?>
+<?rfc compact="no" ?>
+<?rfc subcompact="yes" ?>
+<?rfc iprnotified="yes" ?>
+
+  <front>
+    <title abbrev="RTP Payload Format for Opus Codec">
+      RTP Payload Format for Opus Speech and Audio Codec
+    </title>
+
+    <author fullname="Julian Spittka" initials="J." surname="Spittka">
+      <address>
+        <email>jspittka@gmail.com</email>
+      </address>
+    </author>
+
+    <author initials='K.' surname='Vos' fullname='Koen Vos'>
+      <organization>Skype Technologies S.A.</organization>
+      <address>
+        <postal>
+          <street>3210 Porter Drive</street>
+          <code>94304</code>
+          <city>Palo Alto</city>
+          <region>CA</region>
+          <country>USA</country>
+        </postal>
+        <email>koenvos74@gmail.com</email>
+      </address>
+    </author>
+
+    <author initials="JM" surname="Valin" fullname="Jean-Marc Valin">
+      <organization>Mozilla</organization>
+      <address>
+        <postal>
+          <street>650 Castro Street</street>
+          <city>Mountain View</city>
+          <region>CA</region>
+          <code>94041</code>
+          <country>USA</country>
+        </postal>
+        <email>jmvalin@jmvalin.ca</email>
+      </address>
+    </author>
+
+    <date day='2' month='August' year='2013' />
+
+    <abstract>
+      <t>
+        This document defines the Real-time Transport Protocol (RTP) payload
+        format for packetization of Opus encoded
+        speech and audio data that is essential to integrate the codec in the
+        most compatible way. Further, media type registrations
+        are described for the RTP payload format.
+      </t>
+    </abstract>
+  </front>
+
+  <middle>
+    <section title='Introduction'>
+      <t>
+        The Opus codec is a speech and audio codec developed within the
+        IETF Internet Wideband Audio Codec working group (codec). The codec
+        has a very low algorithmic delay and it
+        is highly scalable in terms of audio bandwidth, bitrate, and
+        complexity. Further, it provides different modes to efficiently encode speech signals
+        as well as music signals, thus, making it the codec of choice for
+        various applications using the Internet or similar networks.
+      </t>
+      <t>
+        This document defines the Real-time Transport Protocol (RTP)
+        <xref target="RFC3550"/> payload format for packetization
+        of Opus encoded speech and audio data that is essential to
+        integrate the Opus codec in the
+        most compatible way. Further, media type registrations are described for
+        the RTP payload format. More information on the Opus
+        codec can be obtained from <xref target="RFC6716"/>.
+      </t>
+    </section>
+
+    <section title='Conventions, Definitions and Acronyms used in this document'>
+      <t>The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+      "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+      document are to be interpreted as described in <xref target="RFC2119"/>.</t>
+      <t>
+      <list style='hanging'>
+          <t hangText="CBR:"> Constant bitrate</t>
+          <t hangText="CPU:"> Central Processing Unit</t>
+          <t hangText="DTX:"> Discontinuous transmission</t>
+          <t hangText="FEC:"> Forward error correction</t>
+	      <t hangText="IP:"> Internet Protocol</t>
+	      <t hangText="samples:"> Speech or audio samples (usually per channel)</t>
+	      <t hangText="SDP:"> Session Description Protocol</t>
+          <t hangText="VBR:"> Variable bitrate</t>
+      </list>
+      </t>
+      <section title='Audio Bandwidth'>
+	<t>
+	  Throughout this document, we refer to the following definitions:
+	</t>
+          <texttable anchor='bandwidth_definitions'>
+	    <ttcol align='center'>Abbreviation</ttcol>
+            <ttcol align='center'>Name</ttcol>
+            <ttcol align='center'>Bandwidth</ttcol>
+            <ttcol align='center'>Sampling</ttcol>
+            <c>nb</c>
+            <c>Narrowband</c>
+            <c>0 - 4000</c>
+            <c>8000</c>
+
+            <c>mb</c>
+            <c>Mediumband</c>
+            <c>0 - 6000</c>
+            <c>12000</c>
+
+            <c>wb</c>
+            <c>Wideband</c>
+            <c>0 - 8000</c>
+            <c>16000</c>
+
+            <c>swb</c>
+            <c>Super-wideband</c>
+            <c>0 - 12000</c>
+            <c>24000</c>
+
+            <c>fb</c>
+            <c>Fullband</c>
+            <c>0 - 20000</c>
+            <c>48000</c>
+
+            <postamble>
+              Audio bandwidth naming
+            </postamble>
+          </texttable>
+      </section>
+    </section>
+
+    <section title='Opus Codec'>
+      <t>
+        The Opus <xref target="RFC6716"/> speech and audio codec has been developed to encode speech
+        signals as well as audio signals. Two different modes, a voice mode
+        or an audio mode, may be chosen to allow the most efficient coding
+        dependent on the type of input signal, the sampling frequency of the
+        input signal, and the specific application.
+      </t>
+
+      <t>
+        The voice mode allows efficient encoding of voice signals at lower bit
+        rates while the audio mode is optimized for audio signals at medium and
+        higher bitrates.
+      </t>
+
+      <t>
+        The Opus speech and audio codec is highly scalable in terms of audio
+        bandwidth, bitrate, and complexity. Further, Opus allows
+        transmitting stereo signals.
+      </t>
+
+      <section title='Network Bandwidth'>
+          <t>
+	    Opus supports all bitrates from 6&nbsp;kb/s to 510&nbsp;kb/s.
+	    The bitrate can be changed dynamically within that range.
+	    All
+	    other parameters being
+	    equal, higher bitrate results in higher quality.
+	  </t>
+	  <section title='Recommended Bitrate' anchor='bitrate_by_bandwidth'>
+	  <t>
+	    For a frame size of
+	    20&nbsp;ms, these
+	    are the bitrate "sweet spots" for Opus in various configurations:
+
+          <list style="symbols">
+	    <t>8-12 kb/s for NB speech,</t>
+	    <t>16-20 kb/s for WB speech,</t>
+	    <t>28-40 kb/s for FB speech,</t>
+	    <t>48-64 kb/s for FB mono music, and</t>
+	    <t>64-128 kb/s for FB stereo music.</t>
+	  </list>
+	</t>
+      </section>
+        <section title='Variable versus Constant Bit Rate'  anchor='variable-vs-constant-bitrate'>
+          <t>
+	    For the same average bitrate, variable bitrate (VBR) can achieve higher quality
+	    than constant bitrate (CBR). For the majority of voice transmission application, VBR
+	    is the best choice. One potential reason for choosing CBR is the potential
+	    information leak that <spanx style='emph'>may</spanx> occur when encrypting the
+	    compressed stream. See <xref target="RFC6562"/> for guidelines on when VBR is
+	    appropriate for encrypted audio communications. In the case where an existing
+	    VBR stream needs to be converted to CBR for security reasons, then the Opus padding
+	    mechanism described in <xref target="RFC6716"/> is the RECOMMENDED way to achieve padding
+	    because the RTP padding bit is unencrypted.</t>
+
+	    <t>
+            The bitrate can be adjusted at any point in time. To avoid congestion,
+            the average bitrate SHOULD be adjusted to the available
+            network capacity. If no target bitrate is specified, the bitrates specified in
+            <xref target='bitrate_by_bandwidth'/> are RECOMMENDED.
+          </t>
+
+        </section>
+
+        <section title='Discontinuous Transmission (DTX)'>
+
+          <t>
+            The Opus codec may, as described in <xref target='variable-vs-constant-bitrate'/>,
+            be operated with an adaptive bitrate. In that case, the bitrate
+            will automatically be reduced for certain input signals like periods
+            of silence. During continuous transmission the bitrate will be
+            reduced, when the input signal allows to do so, but the transmission
+            to the receiver itself will never be interrupted. Therefore, the
+            received signal will maintain the same high level of quality over the
+            full duration of a transmission while minimizing the average bit
+            rate over time.
+          </t>
+
+          <t>
+            In cases where the bitrate of Opus needs to be reduced even
+            further or in cases where only constant bitrate is available,
+            the Opus encoder may be set to use discontinuous
+            transmission (DTX), where parts of the encoded signal that
+            correspond to periods of silence in the input speech or audio signal
+            are not transmitted to the receiver.
+          </t>
+
+          <t>
+            On the receiving side, the non-transmitted parts will be handled by a
+            frame loss concealment unit in the Opus decoder which generates a
+            comfort noise signal to replace the non transmitted parts of the
+            speech or audio signal.
+          </t>
+
+          <t>
+            The DTX mode of Opus will have a slightly lower speech or audio
+            quality than the continuous mode. Therefore, it is RECOMMENDED to
+            use Opus in the continuous mode unless restraints on network
+            capacity are severe. The DTX mode can be engaged for operation
+            in both adaptive or constant bitrate.
+          </t>
+
+        </section>
+
+        </section>
+
+      <section title='Complexity'>
+
+        <t>
+          Complexity can be scaled to optimize for CPU resources in real-time, mostly as
+          a trade-off between audio quality and bitrate. Also, different modes of Opus have different complexity.
+        </t>
+
+      </section>
+
+      <section title="Forward Error Correction (FEC)">
+
+        <t>
+          The voice mode of Opus allows for "in-band" forward error correction (FEC)
+          data to be embedded into the bit stream of Opus. This FEC scheme adds
+          redundant information about the previous packet (n-1) to the current
+          output packet n. For
+          each frame, the encoder decides whether to use FEC based on (1) an
+          externally-provided estimate of the channel's packet loss rate; (2) an
+          externally-provided estimate of the channel's capacity; (3) the
+          sensitivity of the audio or speech signal to packet loss; (4) whether
+          the receiving decoder has indicated it can take advantage of "in-band"
+          FEC information. The decision to send "in-band" FEC information is
+          entirely controlled by the encoder and therefore no special precautions
+          for the payload have to be taken.
+        </t>
+
+        <t>
+          On the receiving side, the decoder can take advantage of this
+          additional information when, in case of a packet loss, the next packet
+          is available.  In order to use the FEC data, the jitter buffer needs
+          to provide access to payloads with the FEC data.  The decoder API function
+          has a flag to indicate that a FEC frame rather than a regular frame should
+          be decoded.  If no FEC data is available for the current frame, the decoder
+          will consider the frame lost and invokes the frame loss concealment.
+        </t>
+
+        <t>
+          If the FEC scheme is not implemented on the receiving side, FEC
+          SHOULD NOT be used, as it leads to an inefficient usage of network
+          resources. Decoder support for FEC SHOULD be indicated at the time a
+          session is set up.
+        </t>
+
+      </section>
+
+      <section title='Stereo Operation'>
+
+        <t>
+          Opus allows for transmission of stereo audio signals. This operation
+          is signaled in-band in the Opus payload and no special arrangement
+          is required in the payload format. Any implementation of the Opus
+          decoder MUST be capable of receiving stereo signals, although it MAY
+	  decode those signals as mono.
+        </t>
+        <t>
+          If a decoder can not take advantage of the benefits of a stereo signal
+          this SHOULD be indicated at the time a session is set up. In that case
+          the sending side SHOULD NOT send stereo signals as it leads to an
+          inefficient usage of the network.
+        </t>
+
+      </section>
+
+    </section>
+
+    <section title='Opus RTP Payload Format' anchor='opus-rtp-payload-format'>
+      <t>The payload format for Opus consists of the RTP header and Opus payload
+      data.</t>
+      <section title='RTP Header Usage'>
+        <t>The format of the RTP header is specified in <xref target="RFC3550"/>. The Opus
+        payload format uses the fields of the RTP header consistent with this
+        specification.</t>
+
+        <t>The payload length of Opus is a multiple number of octets and
+        therefore no padding is required. The payload MAY be padded by an
+        integer number of octets according to <xref target="RFC3550"/>.</t>
+
+        <t>The marker bit (M) of the RTP header is used in accordance with
+	Section 4.1 of <xref target="RFC3551"/>.</t>
+
+        <t>The RTP payload type for Opus has not been assigned statically and is
+        expected to be assigned dynamically.</t>
+
+        <t>The receiving side MUST be prepared to receive duplicates of RTP
+        packets. Only one of those payloads MUST be provided to the Opus decoder
+        for decoding and others MUST be discarded.</t>
+
+        <t>Opus supports 5 different audio bandwidths which may be adjusted during
+        the duration of a call. The RTP timestamp clock frequency is defined as
+        the highest supported sampling frequency of Opus, i.e. 48000 Hz, for all
+        modes and sampling rates of Opus. The unit
+        for the timestamp is samples per single (mono) channel. The RTP timestamp corresponds to the
+        sample time of the first encoded sample in the encoded frame. For sampling
+        rates lower than 48000 Hz the number of samples has to be multiplied with
+        a multiplier according to <xref target="fs-upsample-factors"/> to determine
+        the RTP timestamp.</t>
+
+        <texttable anchor='fs-upsample-factors' title="Timestamp multiplier">
+          <ttcol align='center'>fs (Hz)</ttcol>
+          <ttcol align='center'>Multiplier</ttcol>
+          <c>8000</c>
+          <c>6</c>
+          <c>12000</c>
+          <c>4</c>
+          <c>16000</c>
+          <c>3</c>
+          <c>24000</c>
+          <c>2</c>
+          <c>48000</c>
+          <c>1</c>
+        </texttable>
+      </section>
+
+      <section title='Payload Structure'>
+        <t>
+          The Opus encoder can be set to output encoded frames representing 2.5, 5, 10, 20,
+          40, or 60 ms of speech or audio data. Further, an arbitrary number of frames can be
+          combined into a packet. The maximum packet length is limited to the amount of encoded
+          data representing 120 ms of speech or audio data. The packetization of encoded data
+          is purely done by the Opus encoder and therefore only one packet output from the Opus
+          encoder MUST be used as a payload.
+        </t>
+
+        <t><xref target='payload-structure'/> shows the structure combined with the RTP header.</t>
+
+        <figure anchor="payload-structure"
+                title="Payload Structure with RTP header">
+          <artwork>
+            <![CDATA[
++----------+--------------+
+|RTP Header| Opus Payload |
++----------+--------------+
+           ]]>
+          </artwork>
+        </figure>
+
+        <t>
+          <xref target='opus-packetization'/> shows supported frame sizes in 
+          milliseconds of encoded speech or audio data for speech and audio mode 
+          (Mode) and sampling rates (fs) of Opus and how the timestamp needs to
+          be incremented for packetization (ts incr). If the Opus encoder
+          outputs multiple encoded frames into a single packet the timestamps
+          have to be added up according to the combined frames.
+        </t>
+
+        <texttable anchor='opus-packetization' title="Supported Opus frame 
+         sizes and timestamp increments">
+            <ttcol align='center'>Mode</ttcol>
+            <ttcol align='center'>fs</ttcol>
+            <ttcol align='center'>2.5</ttcol>
+            <ttcol align='center'>5</ttcol>
+            <ttcol align='center'>10</ttcol>
+            <ttcol align='center'>20</ttcol>
+            <ttcol align='center'>40</ttcol>
+            <ttcol align='center'>60</ttcol>
+            <c>ts incr</c>
+            <c>all</c>
+            <c>120</c>
+            <c>240</c>
+            <c>480</c>
+            <c>960</c>
+            <c>1920</c>
+            <c>2880</c>
+            <c>voice</c>
+            <c>nb/mb/wb/swb/fb</c>
+            <c></c>
+            <c></c>
+            <c>x</c>
+            <c>x</c>
+            <c>x</c>
+            <c>x</c>
+            <c>audio</c>
+            <c>nb/wb/swb/fb</c>
+            <c>x</c>
+            <c>x</c>
+            <c>x</c>
+            <c>x</c>
+            <c></c>
+            <c></c>
+          </texttable>
+
+      </section>
+
+    </section>
+
+    <section title='Congestion Control'>
+
+      <t>The adaptive nature of the Opus codec allows for an efficient
+      congestion control.</t>
+
+      <t>The target bitrate of Opus can be adjusted at any point in time and
+      thus allowing for an efficient congestion control. Furthermore, the amount
+      of encoded speech or audio data encoded in a
+      single packet can be used for congestion control since the transmission
+      rate is inversely proportional to these frame sizes. A lower packet
+      transmission rate reduces the amount of header overhead but at the same
+      time increases latency and error sensitivity and should be done with care.</t>
+
+      <t>It is RECOMMENDED that congestion control is applied during the
+      transmission of Opus encoded data.</t>
+    </section>
+
+    <section title='IANA Considerations'>
+      <t>One media subtype (audio/opus) has been defined and registered as
+      described in the following section.</t>
+
+      <section title='Opus Media Type Registration'>
+        <t>Media type registration is done according to <xref
+        target="RFC4288"/> and <xref target="RFC4855"/>.<vspace
+        blankLines='1'/></t>
+
+          <t>Type name: audio<vspace blankLines='1'/></t>
+          <t>Subtype name: opus<vspace blankLines='1'/></t>
+
+          <t>Required parameters:</t>
+          <t><list style="hanging">
+            <t hangText="rate:"> RTP timestamp clock rate is incremented with
+            48000 Hz clock rate for all modes of Opus and all sampling
+            frequencies. For audio sampling rates other than 48000 Hz the rate
+            has to be adjusted to 48000 Hz according to <xref target="fs-upsample-factors"/>.
+          </t>
+          </list></t>
+
+          <t>Optional parameters:</t>
+
+          <t><list style="hanging">
+            <t hangText="maxplaybackrate:">
+              a hint about the maximum output sampling rate that the receiver is
+              capable of rendering in Hz.
+              The decoder MUST be capable of decoding
+              any audio bandwidth but due to hardware limitations only signals
+              up to the specified sampling rate can be played back. Sending signals
+              with higher audio bandwidth results in higher than necessary network
+              usage and encoding complexity, so an encoder SHOULD NOT encode
+              frequencies above the audio bandwidth specified by maxplaybackrate.
+              This parameter can take any value between 8000 and 48000, although
+              commonly the value will match one of the Opus bandwidths 
+              (<xref target="bandwidth_definitions"/>).
+              By default, the receiver is assumed to have no limitations, i.e. 48000.
+              <vspace blankLines='1'/>
+            </t>
+
+            <t hangText="sprop-maxcapturerate:">
+              a hint about the maximum input sampling rate that the sender is likely to produce.
+              This is not a guarantee that the sender will never send any higher bandwidth
+              (e.g. it could send a pre-recorded prompt that uses a higher bandwidth), but it
+              indicates to the receiver that frequencies above this maximum can safely be discarded.
+              This parameter is useful to avoid wasting receiver resources by operating the audio
+              processing pipeline (e.g. echo cancellation) at a higher rate than necessary.
+              This parameter can take any value between 8000 and 48000, although
+              commonly the value will match one of the Opus bandwidths 
+              (<xref target="bandwidth_definitions"/>).
+              By default, the sender is assumed to have no limitations, i.e. 48000.
+              <vspace blankLines='1'/>
+            </t>
+
+            <t hangText="maxptime:"> the decoder's maximum length of time in
+            milliseconds rounded up to the next full integer value represented
+            by the media in a packet that can be
+            encapsulated in a received packet according to Section 6 of
+            <xref target="RFC4566"/>. Possible values are 3, 5, 10, 20, 40,
+            and 60 or an arbitrary multiple of Opus frame sizes rounded up to
+            the next full integer value up to a maximum value of 120 as
+            defined in <xref target='opus-rtp-payload-format'/>. If no value is
+              specified, 120 is assumed as default. This value is a recommendation
+              by the decoding side to ensure the best
+              performance for the decoder. The decoder MUST be
+              capable of accepting any allowed packet sizes to
+              ensure maximum compatibility.
+              <vspace blankLines='1'/></t>
+
+            <t hangText="ptime:"> the decoder's recommended length of time in
+            milliseconds rounded up to the next full integer value represented
+            by the media in a packet according to
+            Section 6 of <xref target="RFC4566"/>. Possible values are
+            3, 5, 10, 20, 40, or 60 or an arbitrary multiple of Opus frame sizes
+            rounded up to the next full integer value up to a maximum
+            value of 120 as defined in <xref
+            target='opus-rtp-payload-format'/>. If no value is
+              specified, 20 is assumed as default. If ptime is greater than
+              maxptime, ptime MUST be ignored. This parameter MAY be changed
+              during a session. This value is a recommendation by the decoding
+              side to ensure the best
+              performance for the decoder. The decoder MUST be
+              capable of accepting any allowed packet sizes to
+              ensure maximum compatibility.
+              <vspace blankLines='1'/></t>
+
+            <t hangText="minptime:"> the decoder's minimum length of time in
+            milliseconds rounded up to the next full integer value represented
+            by the media in a packet that SHOULD
+            be encapsulated in a received packet according to Section 6 of <xref
+            target="RFC4566"/>. Possible values are 3, 5, 10, 20, 40, and 60
+            or an arbitrary multiple of Opus frame sizes rounded up to the next
+            full integer value up to a maximum value of 120
+            as defined in <xref target='opus-rtp-payload-format'/>. If no value is
+              specified, 3 is assumed as default. This value is a recommendation
+              by the decoding side to ensure the best
+              performance for the decoder. The decoder MUST be
+              capable to accept any allowed packet sizes to
+              ensure maximum compatibility.
+              <vspace blankLines='1'/></t>
+
+            <t hangText="maxaveragebitrate:"> specifies the maximum average
+	    receive bitrate of a session in bits per second (b/s). The actual
+            value of the bitrate may vary as it is dependent on the
+            characteristics of the media in a packet. Note that the maximum
+            average bitrate MAY be modified dynamically during a session. Any
+            positive integer is allowed but values outside the range between
+            6000 and 510000 SHOULD be ignored. If no value is specified, the
+            maximum value specified in <xref target='bitrate_by_bandwidth'/>
+            for the corresponding mode of Opus and corresponding maxplaybackrate:
+            will be the default.<vspace blankLines='1'/></t>
+
+            <t hangText="stereo:">
+              specifies whether the decoder prefers receiving stereo or mono signals.
+              Possible values are 1 and 0 where 1 specifies that stereo signals are preferred
+              and 0 specifies that only mono signals are preferred.
+              Independent of the stereo parameter every receiver MUST be able to receive and
+              decode stereo signals but sending stereo signals to a receiver that signaled a
+              preference for mono signals may result in higher than necessary network
+              utilisation and encoding complexity. If no value is specified, mono
+              is assumed (stereo=0).<vspace blankLines='1'/>
+            </t>
+
+            <t hangText="sprop-stereo:">
+              specifies whether the sender is likely to produce stereo audio.
+              Possible values are 1 and 0 where 1 specifies that stereo signals are likely to
+	      be sent, and 0 speficies that the sender will likely only send mono.
+	      This is not a guarantee that the sender will never send stereo audio
+	      (e.g. it could send a pre-recorded prompt that uses stereo), but it
+	      indicates to the receiver that the received signal can be safely downmixed to mono.
+	      This parameter is useful to avoid wasting receiver resources by operating the audio
+	      processing pipeline (e.g. echo cancellation) in stereo when not necessary.
+              If no value is specified, mono
+              is assumed (sprop-stereo=0).<vspace blankLines='1'/>
+            </t>
+
+            <t hangText="cbr:">
+              specifies if the decoder prefers the use of a constant bitrate versus
+              variable bitrate. Possible values are 1 and 0 where 1 specifies constant
+              bitrate and 0 specifies variable bitrate. If no value is specified, cbr
+              is assumed to be 0. Note that the maximum average bitrate may still be
+              changed, e.g. to adapt to changing network conditions.<vspace blankLines='1'/>
+            </t>
+
+            <t hangText="useinbandfec:"> specifies that the decoder has the capability to
+            take advantage of the Opus in-band FEC. Possible values are 1 and 0. It is RECOMMENDED to provide
+            0 in case FEC cannot be utilized on the receiving side. If no
+            value is specified, useinbandfec is assumed to be 0.
+            This parameter is only a preference and the receiver MUST be able to process
+            packets that include FEC information, even if it means the FEC part is discarded.
+            <vspace blankLines='1'/></t>
+
+            <t hangText="usedtx:"> specifies if the decoder prefers the use of
+            DTX. Possible values are 1 and 0. If no value is specified, usedtx
+            is assumed to be 0.<vspace blankLines='1'/></t>
+          </list></t>
+
+          <t>Encoding considerations:<vspace blankLines='1'/></t>
+          <t><list style="hanging">
+            <t>Opus media type is framed and consists of binary data according
+            to Section 4.8 in <xref target="RFC4288"/>.</t>
+          </list></t>
+
+          <t>Security considerations: </t>
+          <t><list style="hanging">
+            <t>See <xref target='security-considerations'/> of this document.</t>
+          </list></t>
+
+          <t>Interoperability considerations: none<vspace blankLines='1'/></t>
+          <t>Published specification: none<vspace blankLines='1'/></t>
+
+          <t>Applications that use this media type: </t>
+          <t><list style="hanging">
+            <t>Any application that requires the transport of
+            speech or audio data may use this media type. Some examples are,
+            but not limited to, audio and video conferencing, Voice over IP,
+            media streaming.</t>
+          </list></t>
+
+          <t>Person &amp; email address to contact for further information:</t>
+          <t><list style="hanging">
+            <t>SILK Support silksupport@skype.net</t>
+            <t>Jean-Marc Valin jmvalin@jmvalin.ca</t>
+          </list></t>
+
+          <t>Intended usage: COMMON<vspace blankLines='1'/></t>
+
+          <t>Restrictions on usage:<vspace blankLines='1'/></t>
+
+          <t><list style="hanging">
+            <t>For transfer over RTP, the RTP payload format (<xref
+            target='opus-rtp-payload-format'/> of this document) SHALL be
+            used.</t>
+          </list></t>
+
+          <t>Author:</t>
+          <t><list style="hanging">
+            <t>Julian Spittka jspittka@gmail.com<vspace blankLines='1'/></t>
+            <t>Koen Vos koenvos74@gmail.com<vspace blankLines='1'/></t>
+            <t>Jean-Marc Valin jmvalin@jmvalin.ca<vspace blankLines='1'/></t>
+          </list></t>
+
+          <t> Change controller: TBD</t>
+      </section>
+
+      <section title='Mapping to SDP Parameters'>
+        <t>The information described in the media type specification has a
+        specific mapping to fields in the Session Description Protocol (SDP)
+        <xref target="RFC4566"/>, which is commonly used to describe RTP
+        sessions. When SDP is used to specify sessions employing the Opus codec,
+        the mapping is as follows:</t>
+
+        <t>
+          <list style="symbols">
+            <t>The media type ("audio") goes in SDP "m=" as the media name.</t>
+
+            <t>The media subtype ("opus") goes in SDP "a=rtpmap" as the encoding
+            name. The RTP clock rate in "a=rtpmap" MUST be 48000 and the number of
+	    channels MUST be 2.</t>
+
+            <t>The OPTIONAL media type parameters "ptime" and "maxptime" are
+            mapped to "a=ptime" and "a=maxptime" attributes, respectively, in the
+            SDP.</t>
+
+            <t>The OPTIONAL media type parameters "maxaveragebitrate", 
+            "maxplaybackrate", "minptime", "stereo", "cbr", "useinbandfec", and 
+            "usedtx", when present, MUST be included in the "a=fmtp" attribute 
+            in the SDP, expressed as a media type string in the form of a
+            semicolon-separated list of parameter=value pairs (e.g.,
+            maxaveragebitrate=20000). They MUST NOT be specified in an
+            SSRC-specific "fmtp" source-level attribute (as defined in
+            Section&nbsp;6.3 of&nbsp;<xref target="RFC5576"/>).</t>
+
+            <t>The OPTIONAL media type parameters "sprop-maxcapturerate",
+            and "sprop-stereo" MAY be mapped to the "a=fmtp" SDP attribute by
+            copying them directly from the media type parameter string as part
+            of the semicolon-separated list of parameter=value pairs (e.g.,
+            sprop-stereo=1). These same OPTIONAL media type parameters MAY also
+            be specified using an SSRC-specific "fmtp" source-level attribute
+            as described in Section&nbsp;6.3 of&nbsp;<xref target="RFC5576"/>.
+            They MAY be specified in both places, in which case the parameter
+            in the source-level attribute overrides the one found on the
+            "a=fmtp" line. The value of any parameter which is not specified in
+            a source-level source attribute MUST be taken from the "a=fmtp"
+            line, if it is present there.</t>
+
+          </list>
+        </t>
+
+        <t>Below are some examples of SDP session descriptions for Opus:</t>
+
+        <t>Example 1: Standard mono session with 48000 Hz clock rate</t>
+          <figure>
+            <artwork>
+              <![CDATA[
+    m=audio 54312 RTP/AVP 101
+    a=rtpmap:101 opus/48000/2
+              ]]>
+            </artwork>
+          </figure>
+
+
+        <t>Example 2: 16000 Hz clock rate, maximum packet size of 40 ms,
+        recommended packet size of 40 ms, maximum average bitrate of 20000 bps,
+        prefers to receive stereo but only plans to send mono, FEC is allowed,
+        DTX is not allowed</t>
+
+        <figure>
+          <artwork>
+            <![CDATA[
+    m=audio 54312 RTP/AVP 101
+    a=rtpmap:101 opus/48000/2
+    a=fmtp:101 maxplaybackrate=16000; sprop-maxcapturerate=16000;
+    maxaveragebitrate=20000; stereo=1; useinbandfec=1; usedtx=0
+    a=ptime:40
+    a=maxptime:40
+            ]]>
+          </artwork>
+        </figure>
+
+        <t>Example 3: Two-way full-band stereo preferred</t>
+
+        <figure>
+          <artwork>
+            <![CDATA[
+    m=audio 54312 RTP/AVP 101
+    a=rtpmap:101 opus/48000/2
+    a=fmtp:101 stereo=1; sprop-stereo=1
+            ]]>
+          </artwork>
+        </figure>
+
+
+      <section title='Offer-Answer Model Considerations for Opus'>
+
+          <t>When using the offer-answer procedure described in <xref
+          target="RFC3264"/> to negotiate the use of Opus, the following
+          considerations apply:</t>
+
+          <t><list style="symbols">
+
+            <t>Opus supports several clock rates. For signaling purposes only
+            the highest, i.e. 48000, is used. The actual clock rate of the
+            corresponding media is signaled inside the payload and is not
+            subject to this payload format description. The decoder MUST be
+            capable to decode every received clock rate. An example
+            is shown below:
+
+            <figure>
+              <artwork>
+                <![CDATA[
+    m=audio 54312 RTP/AVP 100
+    a=rtpmap:100 opus/48000/2
+                ]]>
+              </artwork>
+            </figure>
+            </t>
+
+            <t>The "ptime" and "maxptime" parameters are unidirectional
+            receive-only parameters and typically will not compromise
+            interoperability; however, dependent on the set values of the
+            parameters the performance of the application may suffer.  <xref
+            target="RFC3264"/> defines the SDP offer-answer handling of the
+            "ptime" parameter. The "maxptime" parameter MUST be handled in the
+            same way.</t>
+
+            <t>
+              The "minptime" parameter is a unidirectional
+              receive-only parameters and typically will not compromise
+              interoperability; however, dependent on the set values of the
+              parameter the performance of the application may suffer and should be
+              set with care.
+            </t>
+
+            <t>
+              The "maxplaybackrate" parameter is a unidirectional receive-only
+              parameter that reflects limitations of the local receiver. The sender
+              of the other side SHOULD NOT send with an audio bandwidth higher than
+              "maxplaybackrate" as this would lead to inefficient use of network resources.
+              The "maxplaybackrate" parameter does not
+	      affect interoperability. Also, this parameter SHOULD NOT be used
+	      to adjust the audio bandwidth as a function of the bitrates, as this
+	      is the responsibility of the Opus encoder implementation.
+            </t>
+
+            <t>The "maxaveragebitrate" parameter is a unidirectional receive-only
+            parameter that reflects limitations of the local receiver. The sender
+            of the other side MUST NOT send with an average bitrate higher than
+            "maxaveragebitrate" as it might overload the network and/or
+            receiver. The "maxaveragebitrate" parameter typically will not
+            compromise interoperability; however, dependent on the set value of
+            the parameter the performance of the application may suffer and should
+            be set with care.</t>
+
+            <t>The "sprop-maxcapturerate" and "sprop-stereo" parameters are
+            unidirectional sender-only parameters that reflect limitations of
+            the sender side.
+            They allow the receiver to set up a reduced-complexity audio
+            processing pipeline if the  sender is not planning to use the full
+            range of Opus's capabilities.
+            Neither "sprop-maxcapturerate" nor "sprop-stereo" affect
+            interoperability and the receiver MUST be capable of receiving any signal.
+            </t>
+
+            <t>
+              The "stereo" parameter is a unidirectional receive-only
+              parameter.
+            </t>
+
+            <t>
+              The "cbr" parameter is a unidirectional receive-only
+              parameter.
+            </t>
+
+            <t>The "useinbandfec" parameter is a unidirectional receive-only
+            parameter.</t>
+
+            <t>The "usedtx" parameter is a unidirectional receive-only
+            parameter.</t>
+
+            <t>Any unknown parameter in an offer MUST be ignored by the receiver
+            and MUST be removed from the answer.</t>
+
+          </list></t>
+      </section>
+
+      <section title='Declarative SDP Considerations for Opus'>
+
+        <t>For declarative use of SDP such as in Session Announcement Protocol
+        (SAP), <xref target="RFC2974"/>, and RTSP, <xref target="RFC2326"/>, for
+        Opus, the following needs to be considered:</t>
+
+        <t><list style="symbols">
+
+          <t>The values for "maxptime", "ptime", "minptime", "maxplaybackrate", and
+          "maxaveragebitrate" should be selected carefully to ensure that a
+          reasonable performance can be achieved for the participants of a session.</t>
+
+          <t>
+            The values for "maxptime", "ptime", and "minptime" of the payload
+            format configuration are recommendations by the decoding side to ensure
+            the best performance for the decoder. The decoder MUST be
+            capable to accept any allowed packet sizes to
+            ensure maximum compatibility.
+          </t>
+
+          <t>All other parameters of the payload format configuration are declarative
+          and a participant MUST use the configurations that are provided for
+          the session. More than one configuration may be provided if necessary
+          by declaring multiple RTP payload types; however, the number of types
+          should be kept small.</t>
+        </list></t>
+      </section>
+    </section>
+  </section>
+
+    <section title='Security Considerations' anchor='security-considerations'>
+
+      <t>All RTP packets using the payload format defined in this specification
+      are subject to the general security considerations discussed in the RTP
+      specification <xref target="RFC3550"/> and any profile from
+      e.g. <xref target="RFC3711"/> or <xref target="RFC3551"/>.</t>
+
+      <t>This payload format transports Opus encoded speech or audio data,
+      hence, security issues include confidentiality, integrity protection, and
+      authentication of the speech or audio itself. The Opus payload format does
+      not have any built-in security mechanisms. Any suitable external
+      mechanisms, such as SRTP <xref target="RFC3711"/>, MAY be used.</t>
+
+      <t>This payload format and the Opus encoding do not exhibit any
+      significant non-uniformity in the receiver-end computational load and thus
+      are unlikely to pose a denial-of-service threat due to the receipt of
+      pathological datagrams.</t>
+    </section>
+
+    <section title='Acknowledgements'>
+    <t>TBD</t>
+    </section>
+  </middle>
+
+  <back>
+    <references title="Normative References">
+      &rfc2119;
+      &rfc3550;
+      &rfc3711;
+      &rfc3551;
+      &rfc4288;
+      &rfc4855;
+      &rfc4566;
+      &rfc3264;
+      &rfc2974;
+      &rfc2326;
+      &rfc5576;
+      &rfc6562;
+      &rfc6716;
+    </references>
+
+  </back>
+</rfc>
diff --git a/doc/draft-valin-codec-opus-update.xml b/doc/draft-valin-codec-opus-update.xml
new file mode 100644
index 0000000..b973e28
--- /dev/null
+++ b/doc/draft-valin-codec-opus-update.xml
@@ -0,0 +1,259 @@
+<?xml version="1.0" encoding="US-ASCII"?>
+<!DOCTYPE rfc SYSTEM "rfc2629.dtd">
+<?rfc toc="yes"?>
+<?rfc tocompact="yes"?>
+<?rfc tocdepth="3"?>
+<?rfc tocindent="yes"?>
+<?rfc symrefs="yes"?>
+<?rfc sortrefs="yes"?>
+<?rfc comments="yes"?>
+<?rfc inline="yes"?>
+<?rfc compact="yes"?>
+<?rfc subcompact="no"?>
+<rfc category="std" docName="draft-valin-codec-opus-update-00"
+     ipr="trust200902">
+  <front>
+    <title abbrev="Opus Update">Updates to the Opus Audio Codec</title>
+
+<author initials="JM" surname="Valin" fullname="Jean-Marc Valin">
+<organization>Mozilla Corporation</organization>
+<address>
+<postal>
+<street>650 Castro Street</street>
+<city>Mountain View</city>
+<region>CA</region>
+<code>94041</code>
+<country>USA</country>
+</postal>
+<phone>+1 650 903-0800</phone>
+<email>jmvalin@jmvalin.ca</email>
+</address>
+</author>
+
+<author initials="T." surname="Terriberry" fullname="Timothy B. Terriberry">
+<organization>Mozilla Corporation</organization>
+<address>
+<postal>
+<street>650 Castro Street</street>
+<city>Mountain View</city>
+<region>CA</region>
+<code>94041</code>
+<country>USA</country>
+</postal>
+<phone>+1 650 903-0800</phone>
+<email>tterriberry@mozilla.com</email>
+</address>
+</author>
+
+<author initials="K." surname="Vos" fullname="Koen Vos">
+<organization>Skype Technologies S.A.</organization>
+<address>
+<postal>
+<street>Soder Malarstrand 43</street>
+<city>Stockholm</city>
+<region></region>
+<code>11825</code>
+<country>SE</country>
+</postal>
+<phone>+46 73 085 7619</phone>
+<email>koen.vos@skype.net</email>
+</address>
+</author>
+
+
+
+    <date day="12" month="July" year="2013" />
+
+    <abstract>
+      <t>This document addresses minor issues that were found in the specification
+      of the Opus audio codec in <xref target="RFC6716">RFC 6716</xref>.</t>
+    </abstract>
+  </front>
+
+  <middle>
+    <section title="Introduction">
+      <t>This document address minor issues that were discovered in the reference
+      implementation of the Opus codec that serves as the specification in 
+      <xref target="RFC6716">RFC 6716</xref>. Only issues affecting the decoder are
+      listed here. An up-to-date implementation of the Opus encoder can be found at
+      http://opus-codec.org/. The updated specification remains fully compatible with
+      the original specification and only one of the changes results in any difference
+      in the audio output.
+      </t>
+    </section>
+
+    <section title="Terminology">
+      <t>The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+      "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+      document are to be interpreted as described in <xref
+      target="RFC2119">RFC 2119</xref>.</t>
+    </section>
+
+    <section title="Stereo State Reset in SILK">
+      <t>The reference implementation does not reinitialize the stereo state
+      during a mode switch. The old stereo memory can produce a brief impulse
+      (i.e. single sample) in the decoded audio. This can be fixed by changing
+      silk/dec_API.c at line 72:
+      <figure>
+      <artwork><![CDATA[
+     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;
+ }
+]]></artwork>
+</figure>
+     This change affects the normative part of the decoder. Fortunately,
+     the modified decoder is still compliant with the original specification because
+     it still easily passes the testvectors. For example, for the float decoder
+     at 48 kHz, the opus_compare (arbitrary) "quality score" changes from
+     from 99.9333% to 99.925%.
+      </t>
+    </section>
+
+    <section anchor="padding" title="Parsing of the Opus Packet Padding">
+      <t>It was discovered that some invalid packets of very large size could trigger
+      an out-of-bounds read in the Opus packet parsing code responsible for padding.
+      This is due to an integer overflow if the signaled padding exceeds 2^31-1 bytes
+      (the actual packet may be smaller). The code can be fixed by applying the following
+      changes at line 596 of src/opus_decoder.c:
+      <figure>
+      <artwork><![CDATA[
+       /* Padding flag is bit 6 */
+       if (ch&0x40)
+       {
+-         int padding=0;
+          int p;
+          do {
+             if (len<=0)
+                return OPUS_INVALID_PACKET;
+             p = *data++;
+             len--;
+-            padding += p==255 ? 254: p;
++            len -= p==255 ? 254: p;
+          } while (p==255);
+-         len -= padding;
+       }
+]]></artwork>
+</figure>
+      </t>
+      <t>This packet parsing issue is limited to reading memory up
+         to about 60 kB beyond the compressed buffer. This can only be triggered
+         by a compressed packet more than about 16 MB long, so it's not a problem
+         for RTP. In theory, it <spanx style="emph">could</spanx> crash a file
+         decoder (e.g. Opus in Ogg) if the memory just after the incoming packet
+         is out-of-range, but that could not be achieved when attempted in a production
+         application built using an affected version of the Opus decoder.</t>
+    </section>
+
+    <section anchor="resampler" title="Resampler buffer">
+      <t>The SILK resampler had the following issues:
+        <list style="numbers">
+    <t>The calls to memcpy() were using sizeof(opus_int32), but the type of the
+        local buffer was opus_int16.</t>
+    <t>Because the size was wrong, this potentially allowed the source
+        and destination regions of the memcpy overlap.
+          We <spanx style="emph">believe</spanx> that nSamplesIn is at least fs_in_khZ,
+          which is at least 8.
+       Since RESAMPLER_ORDER_FIR_12 is only 8,that should not be a problem once
+       the type size is fixed.</t>
+          <t>The size of the buffer used RESAMPLER_MAX_BATCH_SIZE_IN, but the
+        data stored in it was actually _twice_ the input batch size
+        (nSamplesIn&lt;&lt;1).</t>
+      </list></t>
+      <t>
+      The fact that the code never produced any error in testing (including when run under the
+      Valgrind memory debugger), suggests that in practice
+     the batch sizes are reasonable enough that none of the issues above
+     was ever a problem. However, proving that is non-obvious.
+    </t>
+    <t>The code can be fixed by applying the following changes to like 70 of silk/resampler_private_IIR_FIR.c:
+<figure>
+<artwork><![CDATA[
+     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;
+-    opus_int16 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + RESAMPLER_ORDER_FIR_12 ];
++    opus_int16 buf[ 2*RESAMPLER_MAX_BATCH_SIZE_IN + RESAMPLER_ORDER_FIR_12 ];
+ 
+     /* Copy buffered samples to start of buffer */
+-    silk_memcpy( buf, S->sFIR, RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
++    silk_memcpy( buf, S->sFIR, 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_int32 ) );
++            silk_memmove( 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, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
++    silk_memcpy( S->sFIR, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
+ }
+]]></artwork>
+</figure>
+    </t>
+    </section>
+    
+    <section title="Downmix to Mono">
+      <t>The last issue is not strictly a bug, but it is an issue that has been reported
+      when downmixing Opus decoded stream to mono, whether this is done inside the decoder
+      or as a post-processing on the stereo decoder output. Opus intensity stereo allows
+      optionally coding the two channels 180-degrees out of phase on a per-band basis. 
+      This provides better stereo quality than forcing the two channels to be in phase,
+      but when the output is downmixed to mono, the energy in the affected bands is cancelled
+      sometimes resulting in audible artefacts.
+      </t>
+      <t>A possible work-around for this issue would be to optionally allow the decoder to
+      not apply the 180-degree phase shift when the output is meant to be downmixed (inside or
+      outside of the decoder).
+      </t>
+    </section>
+    <section anchor="IANA" title="IANA Considerations">
+      <t>This document makes no request of IANA.</t>
+
+      <t>Note to RFC Editor: this section may be removed on publication as an
+      RFC.</t>
+    </section>
+
+    <section anchor="Acknowledgements" title="Acknowledgements">
+      <t>We would like to thank Juri Aedla for reporting the issue with the parsing of
+      the Opus padding.</t>
+    </section>
+  </middle>
+
+  <back>
+    <references title="References">
+      <?rfc include="http://xml.resource.org/public/rfc/bibxml/reference.RFC.2119.xml"?>
+      <?rfc include="http://xml.resource.org/public/rfc/bibxml/reference.RFC.6716.xml"?>
+
+
+    </references>
+  </back>
+</rfc>
diff --git a/doc/footer.html.patch b/doc/footer.html.patch
new file mode 100644
index 0000000..23b29da
--- /dev/null
+++ b/doc/footer.html.patch
@@ -0,0 +1,22 @@
+--- footer.orig.html	2012-06-11 00:32:00.237427961 -0400
++++ footer.html	2012-06-11 00:45:51.518437796 -0400
+@@ -6,11 +6,15 @@
+  </div>
+ <!--END GENERATE_TREEVIEW-->
+ <!--BEGIN !GENERATE_TREEVIEW-->
+-<hr class="footer"/><address class="footer"><small>
+-$generatedby &#160;<a href="http://www.doxygen.org/index.html">
+-<img class="footer" src="$relpath$doxygen.png" alt="doxygen"/>
++<hr class="footer"/>
++<table width="100%"><tbody><tr><td>
++For more information visit the <a href="http://opus-codec.org">Opus Website</a>.
++</td><td><address class="footer"><small>
++&copy;$year<br/>
++$generatedby <a href="http://www.doxygen.org/index.html">
++<!--<img class="footer" src="$relpath$doxygen.png" alt="doxygen"/>-->doxygen
+ </a> $doxygenversion
+-</small></address>
++</small></address></tr></tbody></table>
+ <!--END !GENERATE_TREEVIEW-->
+ </body>
+ </html>
diff --git a/doc/header.html.patch b/doc/header.html.patch
new file mode 100644
index 0000000..4cd76cf
--- /dev/null
+++ b/doc/header.html.patch
@@ -0,0 +1,28 @@
+--- header.orig.html	2012-06-11 00:32:03.320461381 -0400
++++ header.html	2012-06-11 01:08:42.943446484 -0400
+@@ -18,16 +18,21 @@
+ <div id="titlearea">
+ <table cellspacing="0" cellpadding="0">
+  <tbody>
+- <tr style="height: 56px;">
++ <tr style="height: 64px;">
+   <!--BEGIN PROJECT_LOGO-->
+   <td id="projectlogo"><img alt="Logo" src="$relpath$$projectlogo"/></td>
+   <!--END PROJECT_LOGO-->
+   <!--BEGIN PROJECT_NAME-->
+   <td style="padding-left: 0.5em;">
+-   <div id="projectname">$projectname
+-   <!--BEGIN PROJECT_NUMBER-->&#160;<span id="projectnumber">$projectnumber</span><!--END PROJECT_NUMBER-->
+-   </div>
++  <div id="projectname"><img src="opus_logo.svg" width=112 height=64 alt="Opus"/><!--$projectname--></div>
++  </td>
++  <td><table style="padding-left: 0.5em;" cellspacing="0" cellpadding="0"><tbody>
++   <tr><td>
+    <!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF-->
++   </td></tr>
++  <td><!--BEGIN PROJECT_NUMBER--><span id="projectnumber">$projectnumber</span><!--END PROJECT_NUMBER-->
++   </td></tr>
++   </table>
+   </td>
+   <!--END PROJECT_NAME-->
+   <!--BEGIN !PROJECT_NAME-->
diff --git a/include/opus.h b/include/opus.h
index 847a07c..38817b4 100644
--- a/include/opus.h
+++ b/include/opus.h
@@ -520,7 +520,7 @@
   * @param [in] len <tt>opus_int32</tt>: size of data
   * @param [out] out_toc <tt>char*</tt>: TOC pointer
   * @param [out] frames <tt>char*[48]</tt> encapsulated frames
-  * @param [out] size <tt>short[48]</tt> sizes of the encapsulated frames
+  * @param [out] size <tt>opus_int16[48]</tt> sizes of the encapsulated frames
   * @param [out] payload_offset <tt>int*</tt>: returns the position of the payload within the packet (in bytes)
   * @returns number of frames
   */
@@ -529,7 +529,7 @@
    opus_int32 len,
    unsigned char *out_toc,
    const unsigned char *frames[48],
-   short size[48],
+   opus_int16 size[48],
    int *payload_offset
 ) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
 
@@ -566,6 +566,7 @@
   * @param [in] packet <tt>char*</tt>: Opus packet
   * @param [in] len <tt>opus_int32</tt>: Length of packet
   * @returns Number of frames
+  * @retval OPUS_BAD_ARG Insufficient data was passed to the function
   * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
   */
 OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_frames(const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1);
@@ -577,6 +578,7 @@
   *                                     This must be a multiple of 400, or
   *                                     inaccurate results will be returned.
   * @returns Number of samples
+  * @retval OPUS_BAD_ARG Insufficient data was passed to the function
   * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
   */
 OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_samples(const unsigned char packet[], opus_int32 len, opus_int32 Fs) OPUS_ARG_NONNULL(1);
@@ -586,9 +588,24 @@
   * @param [in] packet <tt>char*</tt>: Opus packet
   * @param [in] len <tt>opus_int32</tt>: Length of packet
   * @returns Number of samples
+  * @retval OPUS_BAD_ARG Insufficient data was passed to the function
   * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
   */
 OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_nb_samples(const OpusDecoder *dec, const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
+
+/** Applies soft-clipping to bring a float signal within the [-1,1] range. If
+  * the signal is already in that range, nothing is done. If there are values
+  * outside of [-1,1], then the signal is clipped as smoothly as possible to
+  * both fit in the range and avoid creating excessive distortion in the
+  * process.
+  * @param [in,out] pcm <tt>float*</tt>: Input PCM and modified PCM
+  * @param [in] frame_size <tt>int</tt> Number of samples per channel to process
+  * @param [in] channels <tt>int</tt>: Number of channels
+  * @param [in,out] softclip_mem <tt>float*</tt>: State memory for the soft clipping process (one float per channel, initialized to zero)
+  */
+OPUS_EXPORT void opus_pcm_soft_clip(float *pcm, int frame_size, int channels, float *softclip_mem);
+
+
 /**@}*/
 
 /** @defgroup opus_repacketizer Repacketizer
diff --git a/include/opus_custom.h b/include/opus_custom.h
index e7861d6..6cf3963 100644
--- a/include/opus_custom.h
+++ b/include/opus_custom.h
@@ -42,15 +42,15 @@
 #endif
 
 #ifdef CUSTOM_MODES
-#define OPUS_CUSTOM_EXPORT OPUS_EXPORT
-#define OPUS_CUSTOM_EXPORT_STATIC OPUS_EXPORT
+# define OPUS_CUSTOM_EXPORT OPUS_EXPORT
+# define OPUS_CUSTOM_EXPORT_STATIC OPUS_EXPORT
 #else
-#define OPUS_CUSTOM_EXPORT
-#ifdef CELT_C
-#define OPUS_CUSTOM_EXPORT_STATIC static inline
-#else
-#define OPUS_CUSTOM_EXPORT_STATIC
-#endif
+# define OPUS_CUSTOM_EXPORT
+# ifdef OPUS_BUILD
+#  define OPUS_CUSTOM_EXPORT_STATIC static inline
+# else
+#  define OPUS_CUSTOM_EXPORT_STATIC
+# endif
 #endif
 
 /** @defgroup opus_custom Opus Custom
@@ -126,6 +126,9 @@
   */
 OPUS_CUSTOM_EXPORT void opus_custom_mode_destroy(OpusCustomMode *mode);
 
+
+#if !defined(OPUS_BUILD) || defined(CELT_ENCODER_C)
+
 /* Encoder */
 /** Gets the size of an OpusCustomEncoder structure.
   * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration
@@ -137,21 +140,6 @@
     int channels
 ) OPUS_ARG_NONNULL(1);
 
-/** Creates a new encoder state. Each stream needs its own encoder
-  * state (can't be shared across simultaneous streams).
-  * @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of
-  *  the stream (must be the same characteristics as used for the
-  *  decoder)
-  * @param [in] channels <tt>int</tt>: Number of channels
-  * @param [out] error <tt>int*</tt>: Returns an error code
-  * @return Newly created encoder state.
-*/
-OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomEncoder *opus_custom_encoder_create(
-    const OpusCustomMode *mode,
-    int channels,
-    int *error
-) OPUS_ARG_NONNULL(1);
-
 /** Initializes a previously allocated encoder state
   * The memory pointed to by st must be the size returned by opus_custom_encoder_get_size.
   * This is intended for applications which use their own allocator instead of malloc.
@@ -170,6 +158,25 @@
     int channels
 ) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
 
+#endif
+
+
+/** Creates a new encoder state. Each stream needs its own encoder
+  * state (can't be shared across simultaneous streams).
+  * @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of
+  *  the stream (must be the same characteristics as used for the
+  *  decoder)
+  * @param [in] channels <tt>int</tt>: Number of channels
+  * @param [out] error <tt>int*</tt>: Returns an error code
+  * @return Newly created encoder state.
+*/
+OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomEncoder *opus_custom_encoder_create(
+    const OpusCustomMode *mode,
+    int channels,
+    int *error
+) OPUS_ARG_NONNULL(1);
+
+
 /** Destroys a an encoder state.
   * @param[in] st <tt>OpusCustomEncoder*</tt>: State to be freed.
   */
@@ -229,6 +236,8 @@
   */
 OPUS_CUSTOM_EXPORT int opus_custom_encoder_ctl(OpusCustomEncoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1);
 
+
+#if !defined(OPUS_BUILD) || defined(CELT_DECODER_C)
 /* Decoder */
 
 /** Gets the size of an OpusCustomDecoder structure.
@@ -241,20 +250,6 @@
     int channels
 ) OPUS_ARG_NONNULL(1);
 
-/** Creates a new decoder state. Each stream needs its own decoder state (can't
-  * be shared across simultaneous streams).
-  * @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the
-  *          stream (must be the same characteristics as used for the encoder)
-  * @param [in] channels <tt>int</tt>: Number of channels
-  * @param [out] error <tt>int*</tt>: Returns an error code
-  * @return Newly created decoder state.
-  */
-OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomDecoder *opus_custom_decoder_create(
-    const OpusCustomMode *mode,
-    int channels,
-    int *error
-) OPUS_ARG_NONNULL(1);
-
 /** Initializes a previously allocated decoder state
   * The memory pointed to by st must be the size returned by opus_custom_decoder_get_size.
   * This is intended for applications which use their own allocator instead of malloc.
@@ -273,6 +268,23 @@
     int channels
 ) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
 
+#endif
+
+
+/** Creates a new decoder state. Each stream needs its own decoder state (can't
+  * be shared across simultaneous streams).
+  * @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the
+  *          stream (must be the same characteristics as used for the encoder)
+  * @param [in] channels <tt>int</tt>: Number of channels
+  * @param [out] error <tt>int*</tt>: Returns an error code
+  * @return Newly created decoder state.
+  */
+OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomDecoder *opus_custom_decoder_create(
+    const OpusCustomMode *mode,
+    int channels,
+    int *error
+) OPUS_ARG_NONNULL(1);
+
 /** Destroys a an decoder state.
   * @param[in] st <tt>OpusCustomDecoder*</tt>: State to be freed.
   */
diff --git a/include/opus_defines.h b/include/opus_defines.h
index cdde061..3474e84 100644
--- a/include/opus_defines.h
+++ b/include/opus_defines.h
@@ -64,14 +64,14 @@
 /**Export control for opus functions */
 
 #ifndef OPUS_EXPORT
-# if defined(__GNUC__) && defined(OPUS_BUILD)
-#  define OPUS_EXPORT __attribute__ ((visibility ("default")))
-# elif defined(WIN32) && !defined(__MINGW32__)
+# if defined(WIN32)
 #  ifdef OPUS_BUILD
 #   define OPUS_EXPORT __declspec(dllexport)
 #  else
 #   define OPUS_EXPORT
 #  endif
+# elif defined(__GNUC__) && defined(OPUS_BUILD)
+#  define OPUS_EXPORT __attribute__ ((visibility ("default")))
 # else
 #  define OPUS_EXPORT
 # endif
@@ -148,8 +148,9 @@
 #define OPUS_GET_GAIN_REQUEST                4045 /* Should have been 4035 */
 #define OPUS_SET_LSB_DEPTH_REQUEST           4036
 #define OPUS_GET_LSB_DEPTH_REQUEST           4037
-
 #define OPUS_GET_LAST_PACKET_DURATION_REQUEST 4039
+#define OPUS_SET_EXPERT_FRAME_DURATION_REQUEST 4040
+#define OPUS_GET_EXPERT_FRAME_DURATION_REQUEST 4041
 
 /* Don't use 4045, it's already taken by OPUS_GET_GAIN_REQUEST */
 
@@ -157,6 +158,7 @@
 #define __opus_check_int(x) (((void)((x) == (opus_int32)0)), (opus_int32)(x))
 #define __opus_check_int_ptr(ptr) ((ptr) + ((ptr) - (opus_int32*)(ptr)))
 #define __opus_check_uint_ptr(ptr) ((ptr) + ((ptr) - (opus_uint32*)(ptr)))
+#define __opus_check_val16_ptr(ptr) ((ptr) + ((ptr) - (opus_val16*)(ptr)))
 /** @endcond */
 
 /** @defgroup opus_ctlvalues Pre-defined values for CTL interface
@@ -185,6 +187,15 @@
 #define OPUS_BANDWIDTH_SUPERWIDEBAND         1104 /**<12 kHz bandpass @hideinitializer*/
 #define OPUS_BANDWIDTH_FULLBAND              1105 /**<20 kHz bandpass @hideinitializer*/
 
+#define OPUS_FRAMESIZE_ARG                   5000 /**< Select frame size from the argument (default) */
+#define OPUS_FRAMESIZE_2_5_MS                5001 /**< Use 2.5 ms frames */
+#define OPUS_FRAMESIZE_5_MS                  5002 /**< Use 5 ms frames */
+#define OPUS_FRAMESIZE_10_MS                 5003 /**< Use 10 ms frames */
+#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_VARIABLE              5010 /**< Optimize the frame size dynamically */
+
 /**@}*/
 
 
@@ -525,6 +536,45 @@
   * @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.
+  * It is then the user's responsibility
+  * to verify how much audio was encoded by checking the ToC byte of the encoded
+  * 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
+  * @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_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>
+  * </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
+  * @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_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>
+  * </dl>
+  * @hideinitializer */
+#define OPUS_GET_EXPERT_FRAME_DURATION(x) OPUS_GET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int_ptr(x)
+
 /**@}*/
 
 /** @defgroup opus_genericctls Generic CTLs
diff --git a/include/opus_multistream.h b/include/opus_multistream.h
index 658067f..ae59979 100644
--- a/include/opus_multistream.h
+++ b/include/opus_multistream.h
@@ -205,6 +205,12 @@
       int coupled_streams
 );
 
+OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_surround_encoder_get_size(
+      int channels,
+      int mapping_family
+);
+
+
 /** Allocates and initializes a multistream encoder state.
   * Call opus_multistream_encoder_destroy() to release
   * this object when finished.
@@ -258,6 +264,17 @@
       int *error
 ) OPUS_ARG_NONNULL(5);
 
+OPUS_EXPORT OPUS_WARN_UNUSED_RESULT 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
+) OPUS_ARG_NONNULL(5);
+
 /** Initialize a previously allocated multistream encoder state.
   * The memory pointed to by \a st must be at least the size returned by
   * opus_multistream_encoder_get_size().
@@ -316,6 +333,17 @@
       int application
 ) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6);
 
+OPUS_EXPORT 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
+) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6);
+
 /** Encodes a multistream Opus frame.
   * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.
   * @param[in] pcm <tt>const opus_int16*</tt>: The input signal as interleaved
diff --git a/m4/as-gcc-inline-assembly.m4 b/m4/as-gcc-inline-assembly.m4
new file mode 100644
index 0000000..a6c44a5
--- /dev/null
+++ b/m4/as-gcc-inline-assembly.m4
@@ -0,0 +1,67 @@
+dnl as-gcc-inline-assembly.m4 0.1.0
+
+dnl autostars m4 macro for detection of gcc inline assembly
+
+dnl David Schleef <ds@schleef.org>
+
+dnl AS_COMPILER_FLAG(ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_GCC_INLINE_ASSEMBLY],
+[
+  AC_MSG_CHECKING([if compiler supports gcc-style inline assembly])
+
+  AC_TRY_COMPILE([], [
+#ifdef __GNUC_MINOR__
+#if (__GNUC__ * 1000 + __GNUC_MINOR__) < 3004
+#error GCC before 3.4 has critical bugs compiling inline assembly
+#endif
+#endif
+__asm__ (""::) ], [flag_ok=yes], [flag_ok=no])
+
+  if test "X$flag_ok" = Xyes ; then
+    $1
+    true
+  else
+    $2
+    true
+  fi
+  AC_MSG_RESULT([$flag_ok])
+])
+
+AC_DEFUN([AS_ASM_ARM_NEON],
+[
+  AC_MSG_CHECKING([if assembler supports NEON instructions on ARM])
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[__asm__("vorr d0,d0,d0")])],
+                    [AC_MSG_RESULT([yes])
+                     $1],
+                    [AC_MSG_RESULT([no])
+                     $2])
+])
+
+
+AC_DEFUN([AS_ASM_ARM_MEDIA],
+[
+  AC_MSG_CHECKING([if assembler supports ARMv6 media instructions on ARM])
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[__asm__("shadd8 r3,r3,r3")])],
+                    [AC_MSG_RESULT([yes])
+                     $1],
+                    [AC_MSG_RESULT([no])
+                     $2])
+])
+
+
+AC_DEFUN([AS_ASM_ARM_EDSP],
+[
+  AC_MSG_CHECKING([if assembler supports EDSP instructions on ARM])
+
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[__asm__("qadd r3,r3,r3")])],
+                    [AC_MSG_RESULT([yes])
+                     $1],
+                    [AC_MSG_RESULT([no])
+                     $2])
+])
diff --git a/opus-uninstalled.pc.in b/opus-uninstalled.pc.in
index 36e8db6..3f2d674 100644
--- a/opus-uninstalled.pc.in
+++ b/opus-uninstalled.pc.in
@@ -8,5 +8,5 @@
 Version: @VERSION@
 Requires:
 Conflicts:
-Libs: ${libdir}/libopus.a @PC_LIBM@
+Libs: ${libdir}/libopus.a @LIBM@
 Cflags: -I${pcfiledir}/@top_srcdir@/include
diff --git a/opus.pc.in b/opus.pc.in
index b7d4083..e15c6fe 100644
--- a/opus.pc.in
+++ b/opus.pc.in
@@ -12,5 +12,5 @@
 Requires:
 Conflicts:
 Libs: -L${libdir} -lopus
-Libs.private: @PC_LIBM@
+Libs.private: @LIBM@
 Cflags: -I${includedir}/opus
diff --git a/opus_headers.mk b/opus_headers.mk
index f160710..43a978c 100644
--- a/opus_headers.mk
+++ b/opus_headers.mk
@@ -1,4 +1,7 @@
 OPUS_HEAD = \
 include/opus.h \
 include/opus_multistream.h \
-src/opus_private.h
+src/opus_private.h \
+src/analysis.h \
+src/mlp.h \
+src/tansig_table.h
diff --git a/opus_sources.mk b/opus_sources.mk
index 384b036..e4eeb91 100644
--- a/opus_sources.mk
+++ b/opus_sources.mk
@@ -2,4 +2,11 @@
 src/opus_decoder.c \
 src/opus_encoder.c \
 src/opus_multistream.c \
+src/opus_multistream_encoder.c \
+src/opus_multistream_decoder.c \
 src/repacketizer.c
+
+OPUS_SOURCES_FLOAT = \
+src/analysis.c \
+src/mlp.c \
+src/mlp_data.c
diff --git a/silk/A2NLSF.c b/silk/A2NLSF.c
index 49d5d9d..e84cc46 100644
--- a/silk/A2NLSF.c
+++ b/silk/A2NLSF.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/API.h b/silk/API.h
index 4b8ca12..4fe7629 100644
--- a/silk/API.h
+++ b/silk/API.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/CNG.c b/silk/CNG.c
index d0a619c..d175dd5 100644
--- a/silk/CNG.c
+++ b/silk/CNG.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 /* Generates excitation for CNG LPC synthesis */
 static inline void silk_CNG_exc(
@@ -86,8 +87,8 @@
     opus_int   i, subfr;
     opus_int32 sum_Q6, max_Gain_Q16;
     opus_int16 A_Q12[ MAX_LPC_ORDER ];
-    opus_int32 CNG_sig_Q10[ MAX_FRAME_LENGTH + MAX_LPC_ORDER ];
     silk_CNG_struct *psCNG = &psDec->sCNG;
+    SAVE_STACK;
 
     if( psDec->fs_kHz != psCNG->fs_kHz ) {
         /* Reset state */
@@ -123,6 +124,9 @@
 
     /* Add CNG when packet is lost or during DTX */
     if( psDec->lossCnt ) {
+        VARDECL( opus_int32, CNG_sig_Q10 );
+
+        ALLOC( CNG_sig_Q10, length + MAX_LPC_ORDER, opus_int32 );
 
         /* Generate CNG excitation */
         silk_CNG_exc( CNG_sig_Q10 + MAX_LPC_ORDER, psCNG->CNG_exc_buf_Q14, psCNG->CNG_smth_Gain_Q16, length, &psCNG->rand_seed );
@@ -164,4 +168,5 @@
     } else {
         silk_memset( psCNG->CNG_synth_state, 0, psDec->LPC_order *  sizeof( opus_int32 ) );
     }
+    RESTORE_STACK;
 }
diff --git a/silk/HP_variable_cutoff.c b/silk/HP_variable_cutoff.c
index 199dbb3..bbe10f0 100644
--- a/silk/HP_variable_cutoff.c
+++ b/silk/HP_variable_cutoff.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/Inlines.h b/silk/Inlines.h
index 87ac2e2..244f66f 100644
--- a/silk/Inlines.h
+++ b/silk/Inlines.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/LPC_analysis_filter.c b/silk/LPC_analysis_filter.c
index 421dba0..9d1f16c 100644
--- a/silk/LPC_analysis_filter.c
+++ b/silk/LPC_analysis_filter.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "SigProc_FIX.h"
+#include "celt_lpc.h"
 
 /*******************************************/
 /* LPC analysis filter                     */
@@ -46,14 +47,33 @@
     const opus_int32            d                   /* I    Filter order                                                */
 )
 {
-    opus_int         ix, j;
+    opus_int   j;
+#ifdef FIXED_POINT
+    opus_int16 mem[SILK_MAX_ORDER_LPC];
+    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 );
 
+#ifdef FIXED_POINT
+    silk_assert( d <= SILK_MAX_ORDER_LPC );
+    for ( j = 0; j < d; j++ ) {
+        num[ j ] = -B[ j ];
+    }
+    for (j=0;j<d;j++) {
+        mem[ j ] = in[ d - j - 1 ];
+    }
+    celt_fir( in + d, num, out + d, len - d, d, mem );
+    for ( j = 0; j < d; j++ ) {
+        out[ j ] = 0;
+    }
+#else
     for( ix = d; ix < len; ix++ ) {
         in_ptr = &in[ ix - 1 ];
 
@@ -82,4 +102,5 @@
 
     /* Set first d output samples to zero */
     silk_memset( out, 0, d * sizeof( opus_int16 ) );
+#endif
 }
diff --git a/silk/LPC_inv_pred_gain.c b/silk/LPC_inv_pred_gain.c
index c36f342..4af89aa 100644
--- a/silk/LPC_inv_pred_gain.c
+++ b/silk/LPC_inv_pred_gain.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/LP_variable_cutoff.c b/silk/LP_variable_cutoff.c
index d0912a6..c1ac23e 100644
--- a/silk/LP_variable_cutoff.c
+++ b/silk/LP_variable_cutoff.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/MacroCount.h b/silk/MacroCount.h
index 2829e8c..dbb9775 100644
--- a/silk/MacroCount.h
+++ b/silk/MacroCount.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/MacroDebug.h b/silk/MacroDebug.h
index ecd90bc..9c29576 100644
--- a/silk/MacroDebug.h
+++ b/silk/MacroDebug.h
@@ -9,11 +9,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF2A.c b/silk/NLSF2A.c
index 10b66b6..06635f1 100644
--- a/silk/NLSF2A.c
+++ b/silk/NLSF2A.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF_VQ.c b/silk/NLSF_VQ.c
index 352dda2..69b6e22 100644
--- a/silk/NLSF_VQ.c
+++ b/silk/NLSF_VQ.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF_VQ_weights_laroia.c b/silk/NLSF_VQ_weights_laroia.c
index 05bb17a..04894c5 100644
--- a/silk/NLSF_VQ_weights_laroia.c
+++ b/silk/NLSF_VQ_weights_laroia.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF_decode.c b/silk/NLSF_decode.c
index e007c49..3839acd 100644
--- a/silk/NLSF_decode.c
+++ b/silk/NLSF_decode.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF_del_dec_quant.c b/silk/NLSF_del_dec_quant.c
index 78870de..4139e8f 100644
--- a/silk/NLSF_del_dec_quant.c
+++ b/silk/NLSF_del_dec_quant.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF_encode.c b/silk/NLSF_encode.c
index 52a263d..03a036f 100644
--- a/silk/NLSF_encode.c
+++ b/silk/NLSF_encode.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 /***********************/
 /* NLSF vector encoder */
@@ -46,10 +47,10 @@
 {
     opus_int         i, s, ind1, bestIndex, prob_Q8, bits_q7;
     opus_int32       W_tmp_Q9;
-    opus_int32       err_Q26[      NLSF_VQ_MAX_VECTORS ];
-    opus_int32       RD_Q25[       NLSF_VQ_MAX_SURVIVORS ];
-    opus_int         tempIndices1[ NLSF_VQ_MAX_SURVIVORS ];
-    opus_int8        tempIndices2[ NLSF_VQ_MAX_SURVIVORS * MAX_LPC_ORDER ];
+    VARDECL( opus_int32, err_Q26 );
+    VARDECL( opus_int32, RD_Q25 );
+    VARDECL( opus_int, tempIndices1 );
+    VARDECL( opus_int8, tempIndices2 );
     opus_int16       res_Q15[      MAX_LPC_ORDER ];
     opus_int16       res_Q10[      MAX_LPC_ORDER ];
     opus_int16       NLSF_tmp_Q15[ MAX_LPC_ORDER ];
@@ -58,6 +59,7 @@
     opus_uint8       pred_Q8[      MAX_LPC_ORDER ];
     opus_int16       ec_ix[        MAX_LPC_ORDER ];
     const opus_uint8 *pCB_element, *iCDF_ptr;
+    SAVE_STACK;
 
     silk_assert( nSurvivors <= NLSF_VQ_MAX_SURVIVORS );
     silk_assert( signalType >= 0 && signalType <= 2 );
@@ -67,11 +69,16 @@
     silk_NLSF_stabilize( pNLSF_Q15, psNLSF_CB->deltaMin_Q15, psNLSF_CB->order );
 
     /* First stage: VQ */
+    ALLOC( err_Q26, psNLSF_CB->nVectors, opus_int32 );
     silk_NLSF_VQ( err_Q26, pNLSF_Q15, psNLSF_CB->CB1_NLSF_Q8, psNLSF_CB->nVectors, psNLSF_CB->order );
 
     /* Sort the quantization errors */
+    ALLOC( tempIndices1, nSurvivors, opus_int );
     silk_insertion_sort_increasing( err_Q26, 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 ];
@@ -124,5 +131,6 @@
     /* Decode */
     silk_NLSF_decode( pNLSF_Q15, NLSFIndices, psNLSF_CB );
 
+    RESTORE_STACK;
     return RD_Q25[ 0 ];
 }
diff --git a/silk/NLSF_stabilize.c b/silk/NLSF_stabilize.c
index 7498b54..1fa1ea3 100644
--- a/silk/NLSF_stabilize.c
+++ b/silk/NLSF_stabilize.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NLSF_unpack.c b/silk/NLSF_unpack.c
index 47f6cfe..17bd23f 100644
--- a/silk/NLSF_unpack.c
+++ b/silk/NLSF_unpack.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/NSQ.c b/silk/NSQ.c
index b49cdf5..4f2b7fe 100644
--- a/silk/NSQ.c
+++ b/silk/NSQ.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 static inline void silk_nsq_scale_states(
     const silk_encoder_state *psEncC,           /* I    Encoder State                   */
@@ -88,11 +89,12 @@
     opus_int            k, lag, start_idx, LSF_interpolation_flag;
     const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
     opus_int16          *pxq;
-    opus_int32          sLTP_Q15[ 2 * MAX_FRAME_LENGTH ];
-    opus_int16          sLTP[     2 * MAX_FRAME_LENGTH ];
+    VARDECL( opus_int32, sLTP_Q15 );
+    VARDECL( opus_int16, sLTP );
     opus_int32          HarmShapeFIRPacked_Q14;
     opus_int            offset_Q10;
-    opus_int32          x_sc_Q10[ MAX_SUB_FRAME_LENGTH ];
+    VARDECL( opus_int32, x_sc_Q10 );
+    SAVE_STACK;
 
     NSQ->rand_seed = psIndices->Seed;
 
@@ -109,6 +111,10 @@
         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;
@@ -160,6 +166,7 @@
     /* DEBUG_STORE_DATA( enc.pcm, &NSQ->xq[ psEncC->ltp_mem_length ], psEncC->frame_length * sizeof( opus_int16 ) ) */
     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;
 }
 
 /***********************************/
diff --git a/silk/NSQ_del_dec.c b/silk/NSQ_del_dec.c
index b877fa9..a1b9606 100644
--- a/silk/NSQ_del_dec.c
+++ b/silk/NSQ_del_dec.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 typedef struct {
     opus_int32 sLPC_Q14[ MAX_SUB_FRAME_LENGTH + NSQ_LPC_BUF_LENGTH ];
@@ -54,6 +55,8 @@
     opus_int32 LPC_exc_Q14;
 } NSQ_sample_struct;
 
+typedef NSQ_sample_struct  NSQ_sample_pair[ 2 ];
+
 static inline void silk_nsq_del_dec_scale_states(
     const silk_encoder_state *psEncC,               /* I    Encoder State                       */
     silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
@@ -123,17 +126,18 @@
 {
     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;
+    const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
     opus_int16          *pxq;
-    opus_int32          sLTP_Q15[ 2 * MAX_FRAME_LENGTH ];
-    opus_int16          sLTP[     2 * MAX_FRAME_LENGTH ];
+    VARDECL( opus_int32, sLTP_Q15 );
+    VARDECL( opus_int16, sLTP );
     opus_int32          HarmShapeFIRPacked_Q14;
     opus_int            offset_Q10;
     opus_int32          RDmin_Q10, Gain_Q10;
-    opus_int32          x_sc_Q10[ MAX_SUB_FRAME_LENGTH ];
-    opus_int32          delayedGain_Q10[  DECISION_DELAY ];
-    NSQ_del_dec_struct  psDelDec[ MAX_DEL_DEC_STATES ];
+    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;
@@ -141,6 +145,7 @@
     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 ];
@@ -175,6 +180,11 @@
         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;
@@ -287,6 +297,7 @@
     /* DEBUG_STORE_DATA( enc.pcm, &NSQ->xq[psEncC->ltp_mem_length], psEncC->frame_length * sizeof( opus_int16 ) ) */
     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;
 }
 
 /******************************************/
@@ -328,11 +339,13 @@
     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 ];
+    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 ];
@@ -614,6 +627,7 @@
         psDD = &psDelDec[ k ];
         silk_memcpy( psDD->sLPC_Q14, &psDD->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
     }
+    RESTORE_STACK;
 }
 
 static inline void silk_nsq_del_dec_scale_states(
diff --git a/silk/PLC.c b/silk/PLC.c
index 8d54729..697ad05 100644
--- a/silk/PLC.c
+++ b/silk/PLC.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/PLC.h b/silk/PLC.h
index 1d2d906..f1e2ecc 100644
--- a/silk/PLC.h
+++ b/silk/PLC.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/SigProc_FIX.h b/silk/SigProc_FIX.h
index daa5fd0..3344ddb 100644
--- a/silk/SigProc_FIX.h
+++ b/silk/SigProc_FIX.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -168,12 +168,6 @@
     const opus_int32            inLog_Q7            /* I  input on log scale                                            */
 );
 
-/* Function that returns the maximum absolut value of the input vector */
-opus_int16 silk_int16_array_maxabs(                 /* O   Maximum absolute value, max: 2^15-1                          */
-    const opus_int16            *vec,               /* I   Input vector  [len]                                          */
-    const opus_int32            len                 /* I   Length of input vector                                       */
-);
-
 /* 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(
@@ -252,7 +246,7 @@
     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_Q15,  /* I    Final 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                                    */
@@ -582,6 +576,14 @@
 #include "MacroCount.h"
 #include "MacroDebug.h"
 
+#ifdef ARMv4_ASM
+#include "arm/SigProc_FIX_armv4.h"
+#endif
+
+#ifdef ARMv5E_ASM
+#include "arm/SigProc_FIX_armv5e.h"
+#endif
+
 #ifdef  __cplusplus
 }
 #endif
diff --git a/silk/VAD.c b/silk/VAD.c
index bac89b4..a9359e9 100644
--- a/silk/VAD.c
+++ b/silk/VAD.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 /* Silk VAD noise level estimation */
 static inline void silk_VAD_GetNoiseLevels(
@@ -82,15 +83,19 @@
 )
 {
     opus_int   SA_Q15, pSNR_dB_Q7, input_tilt;
-    opus_int   decimated_framelength, dec_subframe_length, dec_subframe_offset, SNR_Q7, i, b, s;
+    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;
-    opus_int16 X[ VAD_N_BANDS ][ MAX_FRAME_LENGTH / 2 ];
+    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 );
@@ -101,26 +106,46 @@
     /***********************/
     /* 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[ 0 ][ 0 ], &X[ 3 ][ 0 ], psEncC->frame_length );
+    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[ 0 ][ 0 ], &psSilk_VAD->AnaState1[ 0 ], &X[ 0 ][ 0 ], &X[ 2 ][ 0 ], silk_RSHIFT( psEncC->frame_length, 1 ) );
+    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[ 0 ][ 0 ], &psSilk_VAD->AnaState2[ 0 ], &X[ 0 ][ 0 ], &X[ 1 ][ 0 ], silk_RSHIFT( psEncC->frame_length, 2 ) );
+    silk_ana_filt_bank_1( X, &psSilk_VAD->AnaState2[ 0 ],
+        X, &X[ X_offset[ 1 ] ], decimated_framelength2 );
 
     /*********************************************/
     /* HP filter on lowest band (differentiator) */
     /*********************************************/
-    decimated_framelength = silk_RSHIFT( psEncC->frame_length, 3 );
-    X[ 0 ][ decimated_framelength - 1 ] = silk_RSHIFT( X[ 0 ][ decimated_framelength - 1 ], 1 );
-    HPstateTmp = X[ 0 ][ decimated_framelength - 1 ];
+    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[ 0 ][ i - 1 ]  = silk_RSHIFT( X[ 0 ][ i - 1 ], 1 );
-        X[ 0 ][ i ]     -= X[ 0 ][ i - 1 ];
+        X[ i - 1 ]  = silk_RSHIFT( X[ i - 1 ], 1 );
+        X[ i ]     -= X[ i - 1 ];
     }
-    X[ 0 ][ 0 ] -= psSilk_VAD->HPstate;
+    X[ 0 ] -= psSilk_VAD->HPstate;
     psSilk_VAD->HPstate = HPstateTmp;
 
     /*************************************/
@@ -142,7 +167,8 @@
             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[ b ][ i + dec_subframe_offset ], 3 );
+                x_tmp = silk_RSHIFT(
+                    X[ X_offset[ b ] + i + dec_subframe_offset ], 3 );
                 sumSquared = silk_SMLABB( sumSquared, x_tmp, x_tmp );
 
                 /* Safety check */
@@ -263,6 +289,7 @@
         psEncC->input_quality_bands_Q15[ b ] = silk_sigm_Q15( silk_RSHIFT( SNR_Q7 - 16 * 128, 4 ) );
     }
 
+    RESTORE_STACK;
     return( ret );
 }
 
diff --git a/silk/VQ_WMat_EC.c b/silk/VQ_WMat_EC.c
index a308cfb..c5c6f71 100644
--- a/silk/VQ_WMat_EC.c
+++ b/silk/VQ_WMat_EC.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/ana_filt_bank_1.c b/silk/ana_filt_bank_1.c
index 4e04bef..24cfb03 100644
--- a/silk/ana_filt_bank_1.c
+++ b/silk/ana_filt_bank_1.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/arm/SigProc_FIX_armv4.h b/silk/arm/SigProc_FIX_armv4.h
new file mode 100644
index 0000000..d69573e
--- /dev/null
+++ b/silk/arm/SigProc_FIX_armv4.h
@@ -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 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/silk/arm/SigProc_FIX_armv5e.h b/silk/arm/SigProc_FIX_armv5e.h
new file mode 100644
index 0000000..81a6324
--- /dev/null
+++ b/silk/arm/SigProc_FIX_armv5e.h
@@ -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 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 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/silk/arm/macros_armv4.h b/silk/arm/macros_armv4.h
new file mode 100644
index 0000000..58df6c2
--- /dev/null
+++ b/silk/arm/macros_armv4.h
@@ -0,0 +1,103 @@
+/***********************************************************************
+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
+
+/* (a32 * (opus_int32)((opus_int16)(b32))) >> 16 output have to be 32bit int */
+#undef silk_SMULWB
+static 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"(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 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 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 (rd_hi<<16)+(rd_lo>>16);
+}
+#define silk_SMULWW(a, b) (silk_SMULWW_armv4(a, b))
+
+#undef silk_SMLAWW
+static 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+(rd_hi<<16)+(rd_lo>>16);
+}
+#define silk_SMLAWW(a, b, c) (silk_SMLAWW_armv4(a, b, c))
+
+#endif /* SILK_MACROS_ARMv4_H */
diff --git a/silk/arm/macros_armv5e.h b/silk/arm/macros_armv5e.h
new file mode 100644
index 0000000..63b1e30
--- /dev/null
+++ b/silk/arm/macros_armv5e.h
@@ -0,0 +1,213 @@
+/***********************************************************************
+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
+
+/* (a32 * (opus_int32)((opus_int16)(b32))) >> 16 output have to be 32bit int */
+#undef silk_SMULWB
+static 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 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 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 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 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 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 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 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 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 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 inline opus_int32 silk_CLZ16_armv5(opus_int16 in16)
+{
+  int res;
+  __asm__(
+      "#silk_CLZ16\n\t"
+      "clz %0, %1;\n"
+      : "=r"(res)
+      : "r"(in16<<16|0x8000)
+  );
+  return res;
+}
+#define silk_CLZ16(in16) (silk_CLZ16_armv5(in16))
+
+#undef silk_CLZ32
+static 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))
+
+#endif /* SILK_MACROS_ARMv5E_H */
diff --git a/silk/biquad_alt.c b/silk/biquad_alt.c
index a639e21..d55f5ee 100644
--- a/silk/biquad_alt.c
+++ b/silk/biquad_alt.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/bwexpander.c b/silk/bwexpander.c
index 77ea116..2eb4456 100644
--- a/silk/bwexpander.c
+++ b/silk/bwexpander.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/bwexpander_32.c b/silk/bwexpander_32.c
index 5ad92dd..d0010f7 100644
--- a/silk/bwexpander_32.c
+++ b/silk/bwexpander_32.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/check_control_input.c b/silk/check_control_input.c
index 972a480..b5de9ce 100644
--- a/silk/check_control_input.c
+++ b/silk/check_control_input.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/code_signs.c b/silk/code_signs.c
index 9893cdd..0419ea2 100644
--- a/silk/code_signs.c
+++ b/silk/code_signs.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/control.h b/silk/control.h
index c52ec3f..896cbe8 100644
--- a/silk/control.h
+++ b/silk/control.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/control_SNR.c b/silk/control_SNR.c
index 08e4e1a..f04e69f 100644
--- a/silk/control_SNR.c
+++ b/silk/control_SNR.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/control_audio_bandwidth.c b/silk/control_audio_bandwidth.c
index b645dd5..4f9bc5c 100644
--- a/silk/control_audio_bandwidth.c
+++ b/silk/control_audio_bandwidth.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -115,6 +115,9 @@
                        psEncC->sLP.mode = 1;
                    }
                 }
+            } else {
+               if (psEncC->sLP.mode<0)
+                  psEncC->sLP.mode = 1;
             }
         }
     }
diff --git a/silk/control_codec.c b/silk/control_codec.c
index ecc338c..56ce14c 100644
--- a/silk/control_codec.c
+++ b/silk/control_codec.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -35,6 +35,7 @@
 #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"
 
@@ -137,7 +138,7 @@
 )
 {
     opus_int   ret = SILK_NO_ERROR;
-    opus_int32 nSamples_temp;
+    SAVE_STACK;
 
     if( psEnc->sCmn.fs_kHz != fs_kHz || psEnc->sCmn.prev_API_fs_Hz != psEnc->sCmn.API_fs_Hz )
     {
@@ -145,44 +146,54 @@
             /* 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 {
-            /* Allocate worst case space for temporary upsampling, 8 to 48 kHz, so a factor 6 */
-            opus_int16 x_buf_API_fs_Hz[ ( 2 * MAX_FRAME_LENGTH_MS + LA_SHAPE_MS ) * MAX_API_FS_KHZ ];
-            silk_resampler_state_struct  temp_resampler_state;
+            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
-            opus_int16 x_bufFIX[ 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ];
+            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;
 
-            nSamples_temp = silk_LSHIFT( psEnc->sCmn.frame_length, 1 ) + LA_SHAPE_MS * psEnc->sCmn.fs_kHz;
+            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
-            silk_float2short_array( x_bufFIX, psEnc->x_buf, nSamples_temp );
+            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 */
-            ret += silk_resampler_init( &temp_resampler_state, silk_SMULBB( psEnc->sCmn.fs_kHz, 1000 ), psEnc->sCmn.API_fs_Hz, 0 );
+            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 */
-            ret += silk_resampler( &temp_resampler_state, x_buf_API_fs_Hz, x_bufFIX, nSamples_temp );
-
-            /* Calculate number of samples that has been temporarily upsampled */
-            nSamples_temp = silk_DIV32_16( nSamples_temp * psEnc->sCmn.API_fs_Hz, silk_SMULBB( psEnc->sCmn.fs_kHz, 1000 ) );
+            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, nSamples_temp );
+            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, ( 2 * MAX_FRAME_LENGTH_MS + LA_SHAPE_MS ) * fs_kHz );
+            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;
 }
 
diff --git a/silk/debug.c b/silk/debug.c
index 9aa16cc..9253faf 100644
--- a/silk/debug.c
+++ b/silk/debug.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/debug.h b/silk/debug.h
index 8ae7094..efb6d3e 100644
--- a/silk/debug.h
+++ b/silk/debug.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -28,10 +28,6 @@
 #ifndef SILK_DEBUG_H
 #define SILK_DEBUG_H
 
-#ifdef _WIN32
-#define _CRT_SECURE_NO_DEPRECATE    1
-#endif
-
 #include "typedef.h"
 #include <stdio.h>      /* file writing */
 #include <string.h>     /* strcpy, strcmp */
@@ -69,7 +65,6 @@
 
 #if (defined(_WIN32) || defined(_WINCE))
 #include <windows.h>    /* timer */
-#pragma warning( disable : 4996 )       /* stop bitching about strcpy in TIC()*/
 #else   /* Linux or Mac*/
 #include <sys/time.h>
 #endif
diff --git a/silk/dec_API.c b/silk/dec_API.c
index 68403b7..bb0bc07 100644
--- a/silk/dec_API.c
+++ b/silk/dec_API.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -69,6 +69,9 @@
     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;
 }
@@ -97,6 +100,8 @@
     opus_int stereo_to_mono;
     SAVE_STACK;
 
+    silk_assert( decControl->nChannelsInternal == 1 || decControl->nChannelsInternal == 2 );
+
     /**********************************/
     /* Test if first frame in payload */
     /**********************************/
diff --git a/silk/decode_core.c b/silk/decode_core.c
index 0365ffd..a820bf1 100644
--- a/silk/decode_core.c
+++ b/silk/decode_core.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/decode_frame.c b/silk/decode_frame.c
index 3e4a6e2..abc00a3 100644
--- a/silk/decode_frame.c
+++ b/silk/decode_frame.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/decode_indices.c b/silk/decode_indices.c
index 6917210..7afe5c2 100644
--- a/silk/decode_indices.c
+++ b/silk/decode_indices.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/decode_parameters.c b/silk/decode_parameters.c
index e4c7e7a..e345b1d 100644
--- a/silk/decode_parameters.c
+++ b/silk/decode_parameters.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/decode_pitch.c b/silk/decode_pitch.c
index 80fb4d9..fedbc6a 100644
--- a/silk/decode_pitch.c
+++ b/silk/decode_pitch.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/decode_pulses.c b/silk/decode_pulses.c
index 1c781a0..e8a87c2 100644
--- a/silk/decode_pulses.c
+++ b/silk/decode_pulses.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/decoder_set_fs.c b/silk/decoder_set_fs.c
index 38ac249..eef0fd2 100644
--- a/silk/decoder_set_fs.c
+++ b/silk/decoder_set_fs.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/define.h b/silk/define.h
index f74f486..c47aca9 100644
--- a/silk/define.h
+++ b/silk/define.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/enc_API.c b/silk/enc_API.c
index ec7915c..44b9ab3 100644
--- a/silk/enc_API.c
+++ b/silk/enc_API.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -32,6 +32,7 @@
 #include "API.h"
 #include "control.h"
 #include "typedef.h"
+#include "stack_alloc.h"
 #include "structs.h"
 #include "tuning_parameters.h"
 #ifdef FIXED_POINT
@@ -146,18 +147,21 @@
 )
 {
     opus_int   n, i, nBits, flags, tmp_payloadSize_ms = 0, tmp_complexity = 0, ret = 0;
-    opus_int   nSamplesToBuffer, nBlocksOf10ms, nSamplesFromInput = 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;
-    opus_int16 buf[ MAX_FRAME_LENGTH_MS * MAX_API_FS_KHZ ];
+    VARDECL( opus_int16, buf );
     opus_int transition, curr_block, tot_blocks;
+    SAVE_STACK;
 
     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;
     }
 
@@ -191,9 +195,9 @@
     if( prefillFlag ) {
         /* Only accept input length of 10 ms */
         if( nBlocksOf10ms != 1 ) {
-            ret = SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
             silk_assert( 0 );
-            return ret;
+            RESTORE_STACK;
+            return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
         }
         /* Reset Encoder */
         for( n = 0; n < encControl->nChannelsInternal; n++ ) {
@@ -212,15 +216,15 @@
     } else {
         /* Only accept input lengths that are a multiple of 10 ms */
         if( nBlocksOf10ms * encControl->API_sampleRate != 100 * nSamplesIn || nSamplesIn < 0 ) {
-            ret = SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
             silk_assert( 0 );
-            return ret;
+            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 ) {
-            ret = SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
             silk_assert( 0 );
-            return ret;
+            RESTORE_STACK;
+            return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
         }
     }
 
@@ -230,6 +234,7 @@
         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, TargetRate_bps, 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 ) {
@@ -242,9 +247,16 @@
     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, 10 * nBlocksOf10ms * psEnc->state_Fxx[ 0 ].sCmn.fs_kHz );
+        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 ) {
@@ -533,6 +545,7 @@
         }
     }
 
+    RESTORE_STACK;
     return ret;
 }
 
diff --git a/silk/encode_indices.c b/silk/encode_indices.c
index 91e28aa..666c8c0 100644
--- a/silk/encode_indices.c
+++ b/silk/encode_indices.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/encode_pulses.c b/silk/encode_pulses.c
index b01b585..d1b2f5d 100644
--- a/silk/encode_pulses.c
+++ b/silk/encode_pulses.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 /*********************************************/
 /* Encode quantization indices of excitation */
@@ -66,14 +67,15 @@
 {
     opus_int   i, k, j, iter, bit, nLS, scale_down, RateLevelIndex = 0;
     opus_int32 abs_q, minSumBits_Q5, sumBits_Q5;
-    opus_int   abs_pulses[ MAX_FRAME_LENGTH ];
-    opus_int   sum_pulses[ MAX_NB_SHELL_BLOCKS ];
-    opus_int   nRshifts[   MAX_NB_SHELL_BLOCKS ];
+    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*/
 
@@ -90,6 +92,8 @@
     }
 
     /* 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 ] );
@@ -98,6 +102,8 @@
     }
 
     /* 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;
@@ -196,4 +202,5 @@
     /* Encode signs */
     /****************/
     silk_encode_signs( psRangeEnc, pulses, frame_length, signalType, quantOffsetType, sum_pulses );
+    RESTORE_STACK;
 }
diff --git a/silk/errors.h b/silk/errors.h
index 0591e00..4507080 100644
--- a/silk/errors.h
+++ b/silk/errors.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/LTP_analysis_filter_FIX.c b/silk/fixed/LTP_analysis_filter_FIX.c
index a8fee55..a941908 100644
--- a/silk/fixed/LTP_analysis_filter_FIX.c
+++ b/silk/fixed/LTP_analysis_filter_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/LTP_scale_ctrl_FIX.c b/silk/fixed/LTP_scale_ctrl_FIX.c
index ac2fba1..3dcedef 100644
--- a/silk/fixed/LTP_scale_ctrl_FIX.c
+++ b/silk/fixed/LTP_scale_ctrl_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/apply_sine_window_FIX.c b/silk/fixed/apply_sine_window_FIX.c
index 897fdc3..4502b71 100644
--- a/silk/fixed/apply_sine_window_FIX.c
+++ b/silk/fixed/apply_sine_window_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/autocorr_FIX.c b/silk/fixed/autocorr_FIX.c
index c2ebb6a..dec3cc0 100644
--- a/silk/fixed/autocorr_FIX.c
+++ b/silk/fixed/autocorr_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "SigProc_FIX.h"
+#include "celt_lpc.h"
 
 /* Compute autocorrelation */
 void silk_autocorr(
@@ -40,37 +41,7 @@
     const opus_int              correlationCount    /* I    Number of correlation taps to compute                       */
 )
 {
-    opus_int   i, lz, nRightShifts, corrCount;
-    opus_int64 corr64;
-
+    opus_int   corrCount;
     corrCount = silk_min_int( inputDataSize, correlationCount );
-
-    /* compute energy (zero-lag correlation) */
-    corr64 = silk_inner_prod16_aligned_64( inputData, inputData, inputDataSize );
-
-    /* deal with all-zero input data */
-    corr64 += 1;
-
-    /* number of leading zeros */
-    lz = silk_CLZ64( corr64 );
-
-    /* scaling: number of right shifts applied to correlations */
-    nRightShifts = 35 - lz;
-    *scale = nRightShifts;
-
-    if( nRightShifts <= 0 ) {
-        results[ 0 ] = silk_LSHIFT( (opus_int32)silk_CHECK_FIT32( corr64 ), -nRightShifts );
-
-        /* compute remaining correlations based on int32 inner product */
-          for( i = 1; i < corrCount; i++ ) {
-            results[ i ] = silk_LSHIFT( silk_inner_prod_aligned( inputData, inputData + i, inputDataSize - i ), -nRightShifts );
-        }
-    } else {
-        results[ 0 ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( corr64, nRightShifts ) );
-
-        /* compute remaining correlations based on int64 inner product */
-          for( i = 1; i < corrCount; i++ ) {
-            results[ i ] =  (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( silk_inner_prod16_aligned_64( inputData, inputData + i, inputDataSize - i ), nRightShifts ) );
-        }
-    }
+    *scale = _celt_autocorr(inputData, results, NULL, 0, corrCount-1, inputDataSize);
 }
diff --git a/silk/fixed/burg_modified_FIX.c b/silk/fixed/burg_modified_FIX.c
index 26a66b1..f5112b6 100644
--- a/silk/fixed/burg_modified_FIX.c
+++ b/silk/fixed/burg_modified_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -32,6 +32,7 @@
 #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 */
 
@@ -60,6 +61,7 @@
     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 ];
 
     silk_assert( subfr_length * nb_subfr <= MAX_FRAME_SIZE );
 
@@ -93,10 +95,17 @@
         }
     } 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 );
             for( n = 1; n < D + 1; n++ ) {
-                C_first_row[ n - 1 ] += silk_LSHIFT32(
-                    silk_inner_prod_aligned( x_ptr, x_ptr + n, subfr_length - n ), -rshifts );
+               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 );
             }
         }
     }
@@ -263,7 +272,7 @@
             tmp1 = silk_SMLAWW( tmp1, Atmp1, Atmp1 );                                               /* Q16 */
             A_Q16[ k ] = -Atmp1;
         }
-        *res_nrg = silk_SMLAWW( nrg, silk_SMMUL( FIND_LPC_COND_FAC, C0 ), -tmp1 );                  /* Q( -rshifts ) */
+        *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/silk/fixed/corrMatrix_FIX.c b/silk/fixed/corrMatrix_FIX.c
index 2150249..c617270 100644
--- a/silk/fixed/corrMatrix_FIX.c
+++ b/silk/fixed/corrMatrix_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/encode_frame_FIX.c b/silk/fixed/encode_frame_FIX.c
index a37a9f2..cacfd67 100644
--- a/silk/fixed/encode_frame_FIX.c
+++ b/silk/fixed/encode_frame_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #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           */
@@ -84,9 +85,7 @@
 {
     silk_encoder_control_FIX sEncCtrl;
     opus_int     i, iter, maxIter, found_upper, found_lower, ret = 0;
-    opus_int16   *x_frame, *res_pitch_frame;
-    opus_int32   xfw_Q3[ MAX_FRAME_LENGTH ];
-    opus_int16   res_pitch[ 2 * MAX_FRAME_LENGTH + LA_PITCH_MAX ];
+    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;
@@ -95,7 +94,7 @@
     opus_int16   ec_prevLagIndex_copy;
     opus_int     ec_prevSignalType_copy;
     opus_int8    LastGainIndex_copy2;
-    opus_uint8   ec_buf_copy[ 1275 ];
+    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;
@@ -105,9 +104,8 @@
     /**************************************************************/
     /* 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 */
+    /* start of frame to encode */
+    x_frame = psEnc->x_buf + psEnc->sCmn.ltp_mem_length;
 
     /***************************************/
     /* Ensure smooth bandwidth transitions */
@@ -120,6 +118,17 @@
     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_int32, xfw_Q3 );
+        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 */
         /*****************************************/
@@ -143,6 +152,7 @@
         /*****************************************/
         /* Prefiltering for noise shaper         */
         /*****************************************/
+        ALLOC( xfw_Q3, psEnc->sCmn.frame_length, opus_int32 );
         silk_prefilter_FIX( psEnc, &sEncCtrl, xfw_Q3, x_frame );
 
         /****************************************/
@@ -164,6 +174,7 @@
         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;
@@ -299,6 +310,7 @@
     if( psEnc->sCmn.prefillFlag ) {
         /* No payload */
         *pnBytesOut = 0;
+        RESTORE_STACK;
         return ret;
     }
 
@@ -309,6 +321,7 @@
     /* Payload size */
     *pnBytesOut = silk_RSHIFT( ec_tell( psRangeEnc ) + 7, 3 );
 
+    RESTORE_STACK;
     return ret;
 }
 
diff --git a/silk/fixed/find_LPC_FIX.c b/silk/fixed/find_LPC_FIX.c
index 0ed7e84..70cefb6 100644
--- a/silk/fixed/find_LPC_FIX.c
+++ b/silk/fixed/find_LPC_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main_FIX.h"
+#include "stack_alloc.h"
 #include "tuning_parameters.h"
 
 /* Finds LPC vector from correlations, and converts to NLSF */
@@ -51,7 +52,7 @@
     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 ];
-    opus_int16   LPC_res[ MAX_FRAME_LENGTH + MAX_NB_SUBFR * MAX_LPC_ORDER ];
+    SAVE_STACK;
 
     subfr_length = psEncC->subfr_length + psEncC->predictLPCOrder;
 
@@ -62,6 +63,8 @@
     silk_burg_modified( &res_nrg, &res_nrg_Q, a_Q16, x, minInvGain_Q30, subfr_length, psEncC->nb_subfr, psEncC->predictLPCOrder );
 
     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 );
 
@@ -81,6 +84,8 @@
         /* 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 */
@@ -142,4 +147,5 @@
     }
 
     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/silk/fixed/find_LTP_FIX.c b/silk/fixed/find_LTP_FIX.c
index bd21087..8c4d703 100644
--- a/silk/fixed/find_LTP_FIX.c
+++ b/silk/fixed/find_LTP_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/find_pitch_lags_FIX.c b/silk/fixed/find_pitch_lags_FIX.c
index 39c3048..f60b436 100644
--- a/silk/fixed/find_pitch_lags_FIX.c
+++ b/silk/fixed/find_pitch_lags_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main_FIX.h"
+#include "stack_alloc.h"
 #include "tuning_parameters.h"
 
 /* Find pitch lags */
@@ -41,13 +42,15 @@
 )
 {
     opus_int   buf_len, i, scale;
-    opus_int32 thrhld_Q15, res_nrg;
+    opus_int32 thrhld_Q13, res_nrg;
     const opus_int16 *x_buf, *x_buf_ptr;
-    opus_int16 Wsig[      FIND_PITCH_LPC_WIN_MAX ], *Wsig_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  */
@@ -65,6 +68,8 @@
 
     /* Calculate windowed signal */
 
+    ALLOC( Wsig, psEnc->sCmn.pitch_LPC_win_length, opus_int16 );
+
     /* First LA_LTP samples */
     x_buf_ptr = x_buf + buf_len - psEnc->sCmn.pitch_LPC_win_length;
     Wsig_ptr  = Wsig;
@@ -110,19 +115,19 @@
 
     if( psEnc->sCmn.indices.signalType != TYPE_NO_VOICE_ACTIVITY && psEnc->sCmn.first_frame_after_reset == 0 ) {
         /* Threshold for pitch estimator */
-        thrhld_Q15 = SILK_FIX_CONST( 0.6, 15 );
-        thrhld_Q15 = silk_SMLABB( thrhld_Q15, SILK_FIX_CONST( -0.004, 15 ), psEnc->sCmn.pitchEstimationLPCOrder );
-        thrhld_Q15 = silk_SMLABB( thrhld_Q15, SILK_FIX_CONST( -0.1,   7  ), psEnc->sCmn.speech_activity_Q8 );
-        thrhld_Q15 = silk_SMLABB( thrhld_Q15, SILK_FIX_CONST( -0.15,  15 ), silk_RSHIFT( psEnc->sCmn.prevSignalType, 1 ) );
-        thrhld_Q15 = silk_SMLAWB( thrhld_Q15, SILK_FIX_CONST( -0.1,   16 ), psEnc->sCmn.input_tilt_Q15 );
-        thrhld_Q15 = silk_SAT16(  thrhld_Q15 );
+        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_int16)thrhld_Q15, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, psEnc->sCmn.nb_subfr ) == 0 )
+                (opus_int)thrhld_Q13, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, psEnc->sCmn.nb_subfr ) == 0 )
         {
             psEnc->sCmn.indices.signalType = TYPE_VOICED;
         } else {
@@ -134,4 +139,5 @@
         psEnc->sCmn.indices.contourIndex = 0;
         psEnc->LTPCorr_Q15 = 0;
     }
+    RESTORE_STACK;
 }
diff --git a/silk/fixed/find_pred_coefs_FIX.c b/silk/fixed/find_pred_coefs_FIX.c
index 997989b..70d0279 100644
--- a/silk/fixed/find_pred_coefs_FIX.c
+++ b/silk/fixed/find_pred_coefs_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main_FIX.h"
+#include "stack_alloc.h"
 
 void silk_find_pred_coefs_FIX(
     silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
@@ -40,13 +41,14 @@
 )
 {
     opus_int         i;
-    opus_int32       WLTP[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ];
     opus_int32       invGains_Q16[ MAX_NB_SUBFR ], local_gains[ MAX_NB_SUBFR ], Wght_Q15[ MAX_NB_SUBFR ];
     opus_int16       NLSF_Q15[ MAX_LPC_ORDER ];
     const opus_int16 *x_ptr;
-    opus_int16       *x_pre_ptr, LPC_in_pre[ MAX_NB_SUBFR * MAX_LPC_ORDER + MAX_FRAME_LENGTH ];
+    opus_int16       *x_pre_ptr;
+    VARDECL( opus_int16, LPC_in_pre );
     opus_int32       tmp, min_gain_Q16, minInvGain_Q30;
     opus_int         LTP_corrs_rshift[ MAX_NB_SUBFR ];
+    SAVE_STACK;
 
     /* weighting for weighted least squares */
     min_gain_Q16 = silk_int32_MAX >> 6;
@@ -71,12 +73,19 @@
         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, WLTP );
+
         /**********/
         /* VOICED */
         /**********/
         silk_assert( psEnc->sCmn.ltp_mem_length - psEnc->sCmn.predictLPCOrder >= psEncCtrl->pitchL[ 0 ] + LTP_ORDER / 2 );
 
+        ALLOC( WLTP, psEnc->sCmn.nb_subfr * LTP_ORDER * LTP_ORDER, opus_int32 );
+
         /* LTP analysis */
         silk_find_LTP_FIX( psEncCtrl->LTPCoef_Q14, WLTP, &psEncCtrl->LTPredCodGain_Q7,
             res_pitch, psEncCtrl->pitchL, Wght_Q15, psEnc->sCmn.subfr_length,
@@ -133,4 +142,5 @@
 
     /* 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/silk/fixed/k2a_FIX.c b/silk/fixed/k2a_FIX.c
index cadc927..5fee599 100644
--- a/silk/fixed/k2a_FIX.c
+++ b/silk/fixed/k2a_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/k2a_Q16_FIX.c b/silk/fixed/k2a_Q16_FIX.c
index f96f306..3b03987 100644
--- a/silk/fixed/k2a_Q16_FIX.c
+++ b/silk/fixed/k2a_Q16_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/main_FIX.h b/silk/fixed/main_FIX.h
index 369b31e..d999b13 100644
--- a/silk/fixed/main_FIX.h
+++ b/silk/fixed/main_FIX.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/noise_shape_analysis_FIX.c b/silk/fixed/noise_shape_analysis_FIX.c
index d230e48..b97881b 100644
--- a/silk/fixed/noise_shape_analysis_FIX.c
+++ b/silk/fixed/noise_shape_analysis_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #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   */
@@ -156,8 +157,9 @@
     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 ];
-    opus_int16   x_windowed[    SHAPE_LPC_WIN_MAX ];
+    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;
@@ -258,6 +260,7 @@
     /********************************************/
     /* 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;
@@ -437,4 +440,5 @@
         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/silk/fixed/pitch_analysis_core_FIX.c b/silk/fixed/pitch_analysis_core_FIX.c
index d43f444..b6bc0bb 100644
--- a/silk/fixed/pitch_analysis_core_FIX.c
+++ b/silk/fixed/pitch_analysis_core_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -34,15 +34,30 @@
 ********************************************************** */
 #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                                */
 /************************************************************/
-void silk_P_Ana_calc_corr_st3(
-    opus_int32        cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ],/* (O) 3 DIM correlation array */
+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   */
@@ -50,8 +65,8 @@
     opus_int          complexity                       /* I Complexity setting          */
 );
 
-void silk_P_Ana_calc_energy_st3(
-    opus_int32        energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ],/* (O) 3 DIM energy array */
+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 */
@@ -59,12 +74,6 @@
     opus_int          complexity                       /* I Complexity setting          */
 );
 
-opus_int32 silk_P_Ana_find_scaling(
-    const opus_int16  *frame,
-    const opus_int    frame_length,
-    const opus_int    sum_sqr_len
-);
-
 /*************************************************************/
 /*      FIXED POINT CORE PITCH ANALYSIS FUNCTION             */
 /*************************************************************/
@@ -76,36 +85,37 @@
     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_Q15,  /* I    Final 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                                    */
 )
 {
-    opus_int16 frame_8kHz[ PE_MAX_FRAME_LENGTH_ST_2 ];
-    opus_int16 frame_4kHz[ PE_MAX_FRAME_LENGTH_ST_1 ];
+    VARDECL( opus_int16, frame_8kHz );
+    VARDECL( opus_int16, frame_4kHz );
     opus_int32 filt_state[ 6 ];
-    opus_int32 scratch_mem[ 3 * PE_MAX_FRAME_LENGTH ];
-    opus_int16 *input_frame_ptr;
+    const opus_int16 *input_frame_ptr;
     opus_int   i, k, d, j;
-    opus_int16 C[ PE_MAX_NB_SUBFR ][ ( PE_MAX_LAG >> 1 ) + 5 ];
+    VARDECL( opus_int16, C );
+    VARDECL( opus_int32, xcorr32 );
     const opus_int16 *target_ptr, *basis_ptr;
     opus_int32 cross_corr, normalizer, energy, shift, energy_basis, energy_target;
     opus_int   d_srch[ PE_D_SRCH_LENGTH ], Cmax, length_d_srch, length_d_comp;
-    opus_int16 d_comp[ ( PE_MAX_LAG >> 1 ) + 5 ];
-    opus_int32 sum, threshold, temp32, lag_counter;
+    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;
-    opus_int32 energies_st3[  PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ];
-    opus_int32 crosscorr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ];
-    opus_int   frame_length, frame_length_8kHz, frame_length_4kHz, max_sum_sq_length;
-    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_int32 contour_bias_Q20, diff, lz, lshift;
+    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_Q15, corr_thres_Q15;
+    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 );
 
@@ -114,25 +124,18 @@
     silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
 
     silk_assert( search_thres1_Q16 >= 0 && search_thres1_Q16 <= (1<<16) );
-    silk_assert( search_thres2_Q15 >= 0 && search_thres2_Q15 <= (1<<15) );
+    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;
-    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;
-
-    silk_memset( C, 0, sizeof( opus_int16 ) * nb_subfr * ( ( PE_MAX_LAG >> 1 ) + 5) );
 
     /* Resample from input sampled at Fs_kHz to 8 kHz */
+    ALLOC( frame_8kHz, frame_length_8kHz, opus_int16 );
     if( Fs_kHz == 16 ) {
         silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) );
         silk_resampler_down2( filt_state, frame_8kHz, frame, frame_length );
@@ -146,6 +149,7 @@
 
     /* 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 */
@@ -159,9 +163,9 @@
     *******************************************************************************/
 
     /* Inner product is calculated with different lengths, so scale for the worst case */
-    max_sum_sq_length = silk_max_32( sf_length_8kHz, silk_LSHIFT( sf_length_4kHz, 2 ) );
-    shift = silk_P_Ana_find_scaling( frame_4kHz, frame_length_4kHz, max_sum_sq_length );
+    silk_sum_sqr_shift( &energy, &shift, frame_4kHz, frame_length_4kHz );
     if( shift > 0 ) {
+        shift = silk_RSHIFT( shift, 1 );
         for( i = 0; i < frame_length_4kHz; i++ ) {
             frame_4kHz[ i ] = silk_RSHIFT( frame_4kHz[ i ], shift );
         }
@@ -170,94 +174,93 @@
     /******************************************************************************
     * FIRST STAGE, operating in 4 khz
     ******************************************************************************/
-    target_ptr = &frame_4kHz[ silk_LSHIFT( sf_length_4kHz, 2 ) ];
+    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 );
+        silk_assert( target_ptr + SF_LENGTH_8KHZ <= frame_4kHz + frame_length_4kHz );
 
-        basis_ptr = target_ptr - min_lag_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 );
+        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 );
 
         /* Calculate first vector products before loop */
-        cross_corr = silk_inner_prod_aligned( target_ptr, basis_ptr, sf_length_8kHz );
-        normalizer = silk_inner_prod_aligned( basis_ptr,  basis_ptr, sf_length_8kHz );
-        normalizer = silk_ADD_SAT32( normalizer, silk_SMULBB( sf_length_8kHz, 4000 ) );
+        cross_corr = xcorr32[ MAX_LAG_4KHZ - MIN_LAG_4KHZ ];
+        normalizer = silk_inner_prod_aligned( target_ptr, target_ptr, SF_LENGTH_8KHZ );
+        normalizer = silk_ADD32( normalizer, silk_inner_prod_aligned( basis_ptr,  basis_ptr, SF_LENGTH_8KHZ ) );
+        normalizer = silk_ADD32( normalizer, silk_SMULBB( SF_LENGTH_8KHZ, 4000 ) );
 
-        temp32 = silk_DIV32( cross_corr, silk_SQRT_APPROX( normalizer ) + 1 );
-        C[ k ][ min_lag_4kHz ] = (opus_int16)silk_SAT16( temp32 );        /* Q0 */
+        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++ ) {
+        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 );
+            silk_assert( basis_ptr + SF_LENGTH_8KHZ <= frame_4kHz + frame_length_4kHz );
 
-            cross_corr = silk_inner_prod_aligned( target_ptr, basis_ptr, sf_length_8kHz );
+            cross_corr = xcorr32[ MAX_LAG_4KHZ - d ];
 
             /* Add contribution of new sample and remove contribution from oldest sample */
-            normalizer +=
+            normalizer = silk_ADD32( normalizer,
                 silk_SMULBB( basis_ptr[ 0 ], basis_ptr[ 0 ] ) -
-                silk_SMULBB( basis_ptr[ sf_length_8kHz ], basis_ptr[ sf_length_8kHz ] );
+                silk_SMULBB( basis_ptr[ SF_LENGTH_8KHZ ], basis_ptr[ SF_LENGTH_8KHZ ] ) );
 
-            temp32 = silk_DIV32( cross_corr, silk_SQRT_APPROX( normalizer ) + 1 );
-            C[ k ][ d ] = (opus_int16)silk_SAT16( temp32 );                        /* Q0 */
+            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;
+        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)C[ 0 ][ i ] + (opus_int32)C[ 1 ][ i ];                /* Q0 */
-            silk_assert( silk_RSHIFT( sum, 1 ) == silk_SAT16( silk_RSHIFT( sum, 1 ) ) );
-            sum = silk_RSHIFT( sum, 1 );                                           /* Q-1 */
-            silk_assert( silk_LSHIFT( (opus_int32)-i, 4 ) == silk_SAT16( silk_LSHIFT( (opus_int32)-i, 4 ) ) );
-            sum = silk_SMLAWB( sum, sum, silk_LSHIFT( -i, 4 ) );                    /* Q-1 */
-            silk_assert( sum == silk_SAT16( sum ) );
-            C[ 0 ][ i ] = (opus_int16)sum;                                         /* Q-1 */
+        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 = (opus_int32)C[ 0 ][ i ];
-            sum = silk_SMLAWB( sum, sum, silk_LSHIFT( -i, 4 ) );                    /* Q-1 */
-            C[ 0 ][ i ] = (opus_int16)sum;                                         /* Q-1 */
+        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[ 0 ][ min_lag_4kHz ], d_srch, max_lag_4kHz - min_lag_4kHz + 1, length_d_srch );
+    silk_insertion_sort_decreasing_int16( C, d_srch, CSTRIDE_4KHZ,
+                                          length_d_srch );
 
     /* Escape if correlation is very low already here */
-    target_ptr = &frame_4kHz[ silk_SMULBB( sf_length_4kHz, nb_subfr ) ];
-    energy = silk_inner_prod_aligned( target_ptr, target_ptr, silk_LSHIFT( sf_length_4kHz, 2 ) );
-    energy = silk_ADD_SAT32( energy, 1000 );                                  /* Q0 */
-    Cmax = (opus_int)C[ 0 ][ min_lag_4kHz ];                                  /* Q-1 */
-    threshold = silk_SMULBB( Cmax, Cmax );                                    /* Q-2 */
-
-    /* Compare in Q-2 domain */
-    if( silk_RSHIFT( energy, 4 + 2 ) > threshold ) {
+    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[ 0 ][ min_lag_4kHz + i ] > threshold ) {
-            d_srch[ i ] = silk_LSHIFT( d_srch[ i ] + min_lag_4kHz, 1 );
+        if( C[ i ] > threshold ) {
+            d_srch[ i ] = silk_LSHIFT( d_srch[ i ] + MIN_LAG_4KHZ, 1 );
         } else {
             length_d_srch = i;
             break;
@@ -265,34 +268,37 @@
     }
     silk_assert( length_d_srch > 0 );
 
-    for( i = min_lag_8kHz - 5; i < max_lag_8kHz + 5; i++ ) {
-        d_comp[ i ] = 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 ] ] = 1;
+        d_comp[ d_srch[ i ] - D_COMP_MIN ] = 1;
     }
 
     /* Convolution */
-    for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) {
-        d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ];
+    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 ] > 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 = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) {
-        d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ] + d_comp[ i - 3 ];
+    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 < max_lag_8kHz + 4; i++ ) {
-        if( d_comp[ i ] > 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++;
         }
@@ -306,8 +312,9 @@
     ** Scale signal down to avoid correlations measures from overflowing
     *******************************************************************************/
     /* find scaling as max scaling for each subframe */
-    shift = silk_P_Ana_find_scaling( frame_8kHz, frame_length_8kHz, sf_length_8kHz );
+    silk_sum_sqr_shift( &energy, &shift, frame_8kHz, frame_length_8kHz );
     if( shift > 0 ) {
+        shift = silk_RSHIFT( shift, 1 );
         for( i = 0; i < frame_length_8kHz; i++ ) {
             frame_8kHz[ i ] = silk_RSHIFT( frame_8kHz[ i ], shift );
         }
@@ -316,43 +323,37 @@
     /*********************************************************************************
     * 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( opus_int16 ) );
+    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 );
+        silk_assert( target_ptr + SF_LENGTH_8KHZ <= frame_8kHz + frame_length_8kHz );
 
-        energy_target = silk_inner_prod_aligned( target_ptr, target_ptr, sf_length_8kHz );
+        energy_target = silk_ADD32( silk_inner_prod_aligned( target_ptr, target_ptr, SF_LENGTH_8KHZ ), 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 );
+            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 );
-            energy_basis = silk_inner_prod_aligned( basis_ptr,  basis_ptr, sf_length_8kHz );
+            cross_corr = silk_inner_prod_aligned( target_ptr, basis_ptr, SF_LENGTH_8KHZ );
             if( cross_corr > 0 ) {
-                energy = silk_max( energy_target, energy_basis ); /* Find max to make sure first division < 1.0 */
-                lz = silk_CLZ32( cross_corr );
-                lshift = silk_LIMIT_32( lz - 1, 0, 15 );
-                temp32 = silk_DIV32( silk_LSHIFT( cross_corr, lshift ), silk_RSHIFT( energy, 15 - lshift ) + 1 ); /* Q15 */
-                silk_assert( temp32 == silk_SAT16( temp32 ) );
-                temp32 = silk_SMULWB( cross_corr, temp32 ); /* Q(-1), cc * ( cc / max(b, t) ) */
-                temp32 = silk_ADD_SAT32( temp32, temp32 );  /* Q(0) */
-                lz = silk_CLZ32( temp32 );
-                lshift = silk_LIMIT_32( lz - 1, 0, 15 );
-                energy = silk_min( energy_target, energy_basis );
-                C[ k ][ d ] = silk_DIV32( silk_LSHIFT( temp32, lshift ), silk_RSHIFT( energy, 15 - lshift ) + 1 ); /* Q15*/
+                energy_basis = silk_inner_prod_aligned( basis_ptr, basis_ptr, SF_LENGTH_8KHZ );
+                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 {
-                C[ k ][ d ] = 0;
+                matrix_ptr( C, k, d - ( MIN_LAG_8KHZ - 2 ), CSTRIDE_8KHZ ) = 0;
             }
         }
-        target_ptr += sf_length_8kHz;
+        target_ptr += SF_LENGTH_8KHZ;
     }
 
     /* search over lag range and lags codebook */
@@ -374,7 +375,7 @@
     } else {
         prevLag_log2_Q7 = 0;
     }
-    silk_assert( search_thres2_Q15 == silk_SAT16( search_thres2_Q15 ) );
+    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;
@@ -385,12 +386,10 @@
         } else {
             nb_cbk_search = PE_NB_CBKS_STAGE2;
         }
-        corr_thres_Q15 = silk_RSHIFT( silk_SMULBB( search_thres2_Q15, search_thres2_Q15 ), 13 );
     } 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;
-        corr_thres_Q15 = silk_RSHIFT( silk_SMULBB( search_thres2_Q15, search_thres2_Q15 ), 14 );
     }
 
     for( k = 0; k < length_d_srch; k++ ) {
@@ -398,8 +397,13 @@
         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 */
-                CC[ j ] = CC[ j ] + (opus_int32)C[ i ][ d + matrix_ptr( Lag_CB_ptr, i, j, cbk_size )];
+                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 */
@@ -413,25 +417,25 @@
         }
 
         /* Bias towards shorter lags */
-        lag_log2_Q7 = silk_lin2log( (opus_int32)d ); /* Q7 */
+        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, 15 ) == silk_SAT16( nb_subfr * SILK_FIX_CONST( PE_SHORTLAG_BIAS, 15 ) ) );
-        CCmax_new_b = CCmax_new - silk_RSHIFT( silk_SMULBB( nb_subfr * SILK_FIX_CONST( PE_SHORTLAG_BIAS, 15 ), lag_log2_Q7 ), 7 ); /* Q15 */
+        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, 15 ) == silk_SAT16( nb_subfr * SILK_FIX_CONST( PE_PREVLAG_BIAS, 15 ) ) );
+        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_Q15 = silk_RSHIFT( silk_SMULBB( nb_subfr * SILK_FIX_CONST( PE_PREVLAG_BIAS, 15 ), *LTPCorr_Q15 ), 15 ); /* Q15 */
-            prev_lag_bias_Q15 = silk_DIV32( silk_MUL( prev_lag_bias_Q15, delta_lag_log2_sqr_Q7 ), delta_lag_log2_sqr_Q7 + ( 1 << 6 ) );
-            CCmax_new_b -= prev_lag_bias_Q15; /* Q15 */
+            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 > corr_thres_Q15                              &&  /* 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_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;
@@ -446,24 +450,31 @@
         *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 ) {
+        VARDECL( opus_int16, scratch_mem );
         /***************************************************************************/
         /* Scale input signal down to avoid correlations measures from overflowing */
         /***************************************************************************/
         /* find scaling as max scaling for each subframe */
-        shift = silk_P_Ana_find_scaling( frame, frame_length, sf_length );
+        silk_sum_sqr_shift( &energy, &shift, frame, frame_length );
+        ALLOC( scratch_mem, shift > 0 ? frame_length : 0, opus_int16 );
         if( shift > 0 ) {
             /* Move signal to scratch mem because the input signal should be unchanged */
-            /* Reuse the 32 bit scratch mem vector, use a 16 bit pointer from now */
-            input_frame_ptr = (opus_int16*)scratch_mem;
+            shift = silk_RSHIFT( shift, 1 );
             for( i = 0; i < frame_length; i++ ) {
-                input_frame_ptr[ i ] = silk_RSHIFT( frame[ i ], shift );
+                scratch_mem[ i ] = silk_RSHIFT( frame[ i ], shift );
             }
+            input_frame_ptr = scratch_mem;
         } else {
-            input_frame_ptr = (opus_int16*)frame;
+            input_frame_ptr = frame;
         }
 
         /* Search in original signal */
@@ -483,22 +494,13 @@
         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 */
-        silk_assert( silk_LSHIFT( CCmax, 13 ) >= 0 );
-        *LTPCorr_Q15 = (opus_int)silk_SQRT_APPROX( silk_LSHIFT( CCmax, 13 ) ); /* Output normalized correlation */
+        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 ];
         }
-        /* Calculate the correlations and energies needed in stage 3 */
-        silk_P_Ana_calc_corr_st3(  crosscorr_st3, input_frame_ptr, start_lag, sf_length, nb_subfr, complexity );
-        silk_P_Ana_calc_energy_st3( energies_st3, input_frame_ptr, start_lag, sf_length, nb_subfr, complexity );
-
-        lag_counter = 0;
-        silk_assert( lag == silk_SAT16( lag ) );
-        contour_bias_Q20 = silk_DIV32_16( SILK_FIX_CONST( PE_FLATCONTOUR_BIAS, 20 ), lag );
 
         /* Set up codebook parameters according to complexity setting and frame length */
         if( nb_subfr == PE_MAX_NB_SUBFR ) {
@@ -510,41 +512,43 @@
             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, input_frame_ptr, start_lag, sf_length, nb_subfr, complexity );
+        silk_P_Ana_calc_energy_st3( energies_st3, input_frame_ptr, start_lag, sf_length, nb_subfr, complexity );
+
+        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 = &input_frame_ptr[ PE_LTP_MEM_LENGTH_MS * Fs_kHz ];
+        energy_target = silk_ADD32( silk_inner_prod_aligned( target_ptr, target_ptr, nb_subfr * sf_length ), 1 );
         for( d = start_lag; d <= end_lag; d++ ) {
             for( j = 0; j < nb_cbk_search; j++ ) {
                 cross_corr = 0;
-                energy     = 0;
+                energy     = energy_target;
                 for( k = 0; k < nb_subfr; k++ ) {
-                    silk_assert( PE_MAX_NB_SUBFR == 4 );
-                    energy     += silk_RSHIFT( energies_st3[  k ][ j ][ lag_counter ], 2 ); /* use mean, to avoid overflow */
+                    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 );
-                    cross_corr += silk_RSHIFT( crosscorr_st3[ k ][ j ][ lag_counter ], 2 ); /* use mean, to avoid overflow */
                 }
                 if( cross_corr > 0 ) {
-                    /* Divide cross_corr / energy and get result in Q15 */
-                    lz = silk_CLZ32( cross_corr );
-                    /* Divide with result in Q13, cross_corr could be larger than energy */
-                    lshift = silk_LIMIT_32( lz - 1, 0, 13 );
-                    CCmax_new = silk_DIV32( silk_LSHIFT( cross_corr, lshift ), silk_RSHIFT( energy, 13 - lshift ) + 1 );
-                    CCmax_new = silk_SAT16( CCmax_new );
-                    CCmax_new = silk_SMULWB( cross_corr, CCmax_new );
-                    /* Saturate */
-                    if( CCmax_new > silk_RSHIFT( silk_int32_MAX, 3 ) ) {
-                        CCmax_new = silk_int32_MAX;
-                    } else {
-                        CCmax_new = silk_LSHIFT( CCmax_new, 3 );
-                    }
+                    CCmax_new = silk_DIV32_varQ( cross_corr, energy, 13 + 1 );          /* Q13 */
                     /* Reduce depending on flatness of contour */
-                    diff = silk_int16_MAX - silk_RSHIFT( silk_MUL( contour_bias_Q20, j ), 5 ); /* Q20 -> Q15 */
+                    diff = silk_int16_MAX - silk_MUL( contour_bias_Q15, j );            /* Q15 */
                     silk_assert( diff == silk_SAT16( diff ) );
-                    CCmax_new = silk_LSHIFT( silk_SMULWB( CCmax_new, diff ), 1 );
+                    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
-                   ) {
+                if( CCmax_new > CCmax && ( d + silk_CB_lags_stage3[ 0 ][ j ] ) <= max_lag ) {
                     CCmax   = CCmax_new;
                     lag_new = d;
                     CBimax  = j;
@@ -560,27 +564,35 @@
         *lagIndex = (opus_int16)( lag_new - min_lag);
         *contourIndex = (opus_int8)CBimax;
     } else {        /* Fs_kHz == 8 */
-        /* Save Lags and correlation */
-        CCmax = silk_max( CCmax, 0 );
-        *LTPCorr_Q15 = (opus_int)silk_SQRT_APPROX( silk_LSHIFT( CCmax, 13 ) ); /* Output normalized correlation */
+        /* 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 * Fs_kHz );
+            pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], MIN_LAG_8KHZ, PE_MAX_LAG_MS * 8 );
         }
-        *lagIndex = (opus_int16)( lag - min_lag_8kHz );
+        *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),   */
-/*************************************************************************/
-void silk_P_Ana_calc_corr_st3(
-    opus_int32        cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ],/* (O) 3 DIM correlation array */
+/***********************************************************************
+ * 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   */
@@ -588,12 +600,13 @@
     opus_int          complexity                       /* I Complexity setting          */
 )
 {
-    const opus_int16 *target_ptr, *basis_ptr;
-    opus_int32 cross_corr;
+    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;
-    opus_int32 scratch_mem[ SCRATCH_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 );
@@ -610,6 +623,8 @@
         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++ ) {
@@ -618,11 +633,11 @@
         /* 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 );
         for( j = lag_low; j <= lag_high; j++ ) {
-            basis_ptr = target_ptr - ( start_lag + j );
-            cross_corr = silk_inner_prod_aligned( (opus_int16*)target_ptr, (opus_int16*)basis_ptr, sf_length );
             silk_assert( lag_counter < SCRATCH_SIZE );
-            scratch_mem[ lag_counter ] = cross_corr;
+            scratch_mem[ lag_counter ] = xcorr32[ lag_high - j ];
             lag_counter++;
         }
 
@@ -634,32 +649,35 @@
             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 ];
+                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.                                          */
 /********************************************************************/
-void silk_P_Ana_calc_energy_st3(
-    opus_int32        energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ],/* (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          */
+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          */
 )
 {
     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;
-    opus_int32 scratch_mem[ SCRATCH_SIZE ];
+    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 );
@@ -676,6 +694,8 @@
         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;
@@ -709,37 +729,13 @@
             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 );
+                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;
     }
-}
-
-opus_int32 silk_P_Ana_find_scaling(
-    const opus_int16  *frame,
-    const opus_int    frame_length,
-    const opus_int    sum_sqr_len
-)
-{
-    opus_int32 nbits, x_max;
-
-    x_max = silk_int16_array_maxabs( frame, frame_length );
-
-    if( x_max < silk_int16_MAX ) {
-        /* Number of bits needed for the sum of the squares */
-        nbits = 32 - silk_CLZ32( silk_SMULBB( x_max, x_max ) );
-    } else {
-        /* Here we don't know if x_max should have been silk_int16_MAX + 1, so we expect the worst case */
-        nbits = 30;
-    }
-    nbits += 17 - silk_CLZ16( sum_sqr_len );
-
-    /* Without a guarantee of saturation, we need to keep the 31st bit free */
-    if( nbits < 31 ) {
-        return 0;
-    } else {
-        return( nbits - 30 );
-    }
+    RESTORE_STACK;
 }
diff --git a/silk/fixed/prefilter_FIX.c b/silk/fixed/prefilter_FIX.c
index a96f511..1cfe4f9 100644
--- a/silk/fixed/prefilter_FIX.c
+++ b/silk/fixed/prefilter_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main_FIX.h"
+#include "stack_alloc.h"
 #include "tuning_parameters.h"
 
 /* Prefilter for finding Quantizer input signal */
@@ -101,14 +102,17 @@
     opus_int32 *pxw_Q3;
     opus_int   HarmShapeGain_Q12, Tilt_Q14;
     opus_int32 HarmShapeFIRPacked_Q12, LF_shp_Q14;
-    opus_int32 x_filt_Q12[ MAX_SUB_FRAME_LENGTH ];
-    opus_int32 st_res_Q2[ MAX_SUB_FRAME_LENGTH + MAX_LPC_ORDER ];
+    VARDECL( opus_int32, x_filt_Q12 );
+    VARDECL( opus_int32, st_res_Q2 );
     opus_int16 B_Q10[ 2 ];
+    SAVE_STACK;
 
     /* Set up pointers */
     px  = x;
     pxw_Q3 = xw_Q3;
     lag = P->lagPrev;
+    ALLOC( x_filt_Q12, psEnc->sCmn.subfr_length, opus_int32 );
+    ALLOC( st_res_Q2, psEnc->sCmn.subfr_length, opus_int32 );
     for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
         /* Update Variables that change per sub frame */
         if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
@@ -148,6 +152,7 @@
     }
 
     P->lagPrev = psEncCtrl->pitchL[ psEnc->sCmn.nb_subfr - 1 ];
+    RESTORE_STACK;
 }
 
 /* Prefilter for finding Quantizer input signal */
diff --git a/silk/fixed/process_gains_FIX.c b/silk/fixed/process_gains_FIX.c
index 22d3a71..05aba31 100644
--- a/silk/fixed/process_gains_FIX.c
+++ b/silk/fixed/process_gains_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/regularize_correlations_FIX.c b/silk/fixed/regularize_correlations_FIX.c
index 098c150..a2836b0 100644
--- a/silk/fixed/regularize_correlations_FIX.c
+++ b/silk/fixed/regularize_correlations_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/residual_energy16_FIX.c b/silk/fixed/residual_energy16_FIX.c
index d61e849..ebffb2a 100644
--- a/silk/fixed/residual_energy16_FIX.c
+++ b/silk/fixed/residual_energy16_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/residual_energy_FIX.c b/silk/fixed/residual_energy_FIX.c
index f284e51..105ae31 100644
--- a/silk/fixed/residual_energy_FIX.c
+++ b/silk/fixed/residual_energy_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main_FIX.h"
+#include "stack_alloc.h"
 
 /* Calculates residual energies of input subframes where all subframes have LPC_order   */
 /* of preceding samples                                                                 */
@@ -45,14 +46,18 @@
 )
 {
     opus_int         offset, i, j, rshift, lz1, lz2;
-    opus_int16       *LPC_res_ptr, LPC_res[ ( MAX_FRAME_LENGTH + MAX_NB_SUBFR * MAX_LPC_ORDER ) / 2 ];
+    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 );
@@ -88,4 +93,5 @@
         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/silk/fixed/schur64_FIX.c b/silk/fixed/schur64_FIX.c
index 5ff2756..764a10e 100644
--- a/silk/fixed/schur64_FIX.c
+++ b/silk/fixed/schur64_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -56,6 +56,17 @@
     }
 
     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 );
 
@@ -73,5 +84,9 @@
         }
     }
 
-    return( C[ 0 ][ 1 ] );
+    for(; k < order; k++ ) {
+       rc_Q16[ k ] = 0;
+    }
+
+    return silk_max_32( 1, C[ 0 ][ 1 ] );
 }
diff --git a/silk/fixed/schur_FIX.c b/silk/fixed/schur_FIX.c
index 43db501..c4c0ef2 100644
--- a/silk/fixed/schur_FIX.c
+++ b/silk/fixed/schur_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -68,6 +68,16 @@
     }
 
     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 ) );
@@ -87,6 +97,10 @@
         }
     }
 
+    for(; k < order; k++ ) {
+       rc_Q15[ k ] = 0;
+    }
+
     /* return residual energy */
-    return C[ 0 ][ 1 ];
+    return silk_max_32( 1, C[ 0 ][ 1 ] );
 }
diff --git a/silk/fixed/solve_LS_FIX.c b/silk/fixed/solve_LS_FIX.c
index fb913ab..1a39018 100644
--- a/silk/fixed/solve_LS_FIX.c
+++ b/silk/fixed/solve_LS_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main_FIX.h"
+#include "stack_alloc.h"
 #include "tuning_parameters.h"
 
 /*****************************/
@@ -79,11 +80,13 @@
     opus_int32                      *x_Q16                                  /* O    Pointer to x solution vector                                                */
 )
 {
-    opus_int32 L_Q16[  MAX_MATRIX_SIZE * MAX_MATRIX_SIZE ];
+    VARDECL( opus_int32, L_Q16 );
     opus_int32 Y[      MAX_MATRIX_SIZE ];
     inv_D_t   inv_D[  MAX_MATRIX_SIZE ];
+    SAVE_STACK;
 
     silk_assert( M <= MAX_MATRIX_SIZE );
+    ALLOC( L_Q16, M * M, opus_int32 );
 
     /***************************************************
     Factorize A by LDL such that A = L*D*L',
@@ -107,6 +110,7 @@
     x = inv(L') * inv(D) * Y
     *****************************************************/
     silk_LS_SolveLast_FIX( L_Q16, M, Y, x_Q16 );
+    RESTORE_STACK;
 }
 
 static inline void silk_LDL_factorize_FIX(
diff --git a/silk/fixed/structs_FIX.h b/silk/fixed/structs_FIX.h
index 4162608..244b479 100644
--- a/silk/fixed/structs_FIX.h
+++ b/silk/fixed/structs_FIX.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/fixed/vector_ops_FIX.c b/silk/fixed/vector_ops_FIX.c
index d620602..509c8b3 100644
--- a/silk/fixed/vector_ops_FIX.c
+++ b/silk/fixed/vector_ops_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -94,34 +94,3 @@
     }
     return sum;
 }
-
-/* Function that returns the maximum absolut value of the input vector */
-opus_int16 silk_int16_array_maxabs(                 /* O   Maximum absolute value, max: 2^15-1                          */
-    const opus_int16            *vec,               /* I   Input vector  [len]                                          */
-    const opus_int32            len                 /* I   Length of input vector                                       */
-)
-{
-    opus_int32 max = 0, i, lvl = 0, ind;
-    if( len == 0 ) return 0;
-
-    ind = len - 1;
-    max = silk_SMULBB( vec[ ind ], vec[ ind ] );
-    for( i = len - 2; i >= 0; i-- ) {
-        lvl = silk_SMULBB( vec[ i ], vec[ i ] );
-        if( lvl > max ) {
-            max = lvl;
-            ind = i;
-        }
-    }
-
-    /* Do not return 32768, as it will not fit in an int16 so may lead to problems later on */
-    if( max >= 1073676289 ) {           /* (2^15-1)^2 = 1073676289 */
-        return( silk_int16_MAX );
-    } else {
-        if( vec[ ind ] < 0 ) {
-            return( -vec[ ind ] );
-        } else {
-            return(  vec[ ind ] );
-        }
-    }
-}
diff --git a/silk/fixed/warped_autocorrelation_FIX.c b/silk/fixed/warped_autocorrelation_FIX.c
index d7a3944..a4a579b 100644
--- a/silk/fixed/warped_autocorrelation_FIX.c
+++ b/silk/fixed/warped_autocorrelation_FIX.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/LPC_analysis_filter_FLP.c b/silk/float/LPC_analysis_filter_FLP.c
index 9845655..3bb9244 100644
--- a/silk/float/LPC_analysis_filter_FLP.c
+++ b/silk/float/LPC_analysis_filter_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/LPC_inv_pred_gain_FLP.c b/silk/float/LPC_inv_pred_gain_FLP.c
index 8645f77..25178ba 100644
--- a/silk/float/LPC_inv_pred_gain_FLP.c
+++ b/silk/float/LPC_inv_pred_gain_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/LTP_analysis_filter_FLP.c b/silk/float/LTP_analysis_filter_FLP.c
index d3a6a5a..849b7c1 100644
--- a/silk/float/LTP_analysis_filter_FLP.c
+++ b/silk/float/LTP_analysis_filter_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/LTP_scale_ctrl_FLP.c b/silk/float/LTP_scale_ctrl_FLP.c
index f3f0c57..8dbe29d 100644
--- a/silk/float/LTP_scale_ctrl_FLP.c
+++ b/silk/float/LTP_scale_ctrl_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/SigProc_FLP.h b/silk/float/SigProc_FLP.h
index 036b46d..2f5bb4c 100644
--- a/silk/float/SigProc_FLP.h
+++ b/silk/float/SigProc_FLP.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/apply_sine_window_FLP.c b/silk/float/apply_sine_window_FLP.c
index e06333f..6aae57c 100644
--- a/silk/float/apply_sine_window_FLP.c
+++ b/silk/float/apply_sine_window_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/autocorrelation_FLP.c b/silk/float/autocorrelation_FLP.c
index 9ce709e..8b8a9e6 100644
--- a/silk/float/autocorrelation_FLP.c
+++ b/silk/float/autocorrelation_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/burg_modified_FLP.c b/silk/float/burg_modified_FLP.c
index 31c9b22..ea5dc25 100644
--- a/silk/float/burg_modified_FLP.c
+++ b/silk/float/burg_modified_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/bwexpander_FLP.c b/silk/float/bwexpander_FLP.c
index 59ca4ea..d55a4d7 100644
--- a/silk/float/bwexpander_FLP.c
+++ b/silk/float/bwexpander_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/corrMatrix_FLP.c b/silk/float/corrMatrix_FLP.c
index c59f73c..eae6a1c 100644
--- a/silk/float/corrMatrix_FLP.c
+++ b/silk/float/corrMatrix_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/encode_frame_FLP.c b/silk/float/encode_frame_FLP.c
index 23260bc..3221686 100644
--- a/silk/float/encode_frame_FLP.c
+++ b/silk/float/encode_frame_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/energy_FLP.c b/silk/float/energy_FLP.c
index e3eedf9..24b8179 100644
--- a/silk/float/energy_FLP.c
+++ b/silk/float/energy_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/find_LPC_FLP.c b/silk/float/find_LPC_FLP.c
index 66fa7dd..61c1ad9 100644
--- a/silk/float/find_LPC_FLP.c
+++ b/silk/float/find_LPC_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/find_LTP_FLP.c b/silk/float/find_LTP_FLP.c
index 0a3c71b..7229996 100644
--- a/silk/float/find_LTP_FLP.c
+++ b/silk/float/find_LTP_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/find_pitch_lags_FLP.c b/silk/float/find_pitch_lags_FLP.c
index 00862a6..455db82 100644
--- a/silk/float/find_pitch_lags_FLP.c
+++ b/silk/float/find_pitch_lags_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/find_pred_coefs_FLP.c b/silk/float/find_pred_coefs_FLP.c
index 2156893..0c6f0d6 100644
--- a/silk/float/find_pred_coefs_FLP.c
+++ b/silk/float/find_pred_coefs_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/inner_product_FLP.c b/silk/float/inner_product_FLP.c
index 60823d6..029c012 100644
--- a/silk/float/inner_product_FLP.c
+++ b/silk/float/inner_product_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/k2a_FLP.c b/silk/float/k2a_FLP.c
index 6f05d4b..12af4e7 100644
--- a/silk/float/k2a_FLP.c
+++ b/silk/float/k2a_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/levinsondurbin_FLP.c b/silk/float/levinsondurbin_FLP.c
index b4cd34e..f0ba606 100644
--- a/silk/float/levinsondurbin_FLP.c
+++ b/silk/float/levinsondurbin_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/main_FLP.h b/silk/float/main_FLP.h
index 93455d4..dbd34ae 100644
--- a/silk/float/main_FLP.h
+++ b/silk/float/main_FLP.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/noise_shape_analysis_FLP.c b/silk/float/noise_shape_analysis_FLP.c
index 33bfd20..e7c26fc 100644
--- a/silk/float/noise_shape_analysis_FLP.c
+++ b/silk/float/noise_shape_analysis_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/pitch_analysis_core_FLP.c b/silk/float/pitch_analysis_core_FLP.c
index fbff90c..605ea25 100644
--- a/silk/float/pitch_analysis_core_FLP.c
+++ b/silk/float/pitch_analysis_core_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -35,9 +35,9 @@
 #include "SigProc_FLP.h"
 #include "SigProc_FIX.h"
 #include "pitch_est_defines.h"
+#include "pitch.h"
 
 #define SCRATCH_SIZE        22
-#define eps                 1.192092896e-07f
 
 /************************************************************/
 /* Internally used functions                                */
@@ -85,6 +85,7 @@
     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;
@@ -129,8 +130,6 @@
     max_lag_4kHz      = PE_MAX_LAG_MS * 4;
     max_lag_8kHz      = PE_MAX_LAG_MS * 8 - 1;
 
-    silk_memset(C, 0, sizeof(silk_float) * nb_subfr * ((PE_MAX_LAG >> 1) + 5));
-
     /* Resample from input sampled at Fs_kHz to 8 kHz */
     if( Fs_kHz == 16 ) {
         /* Resample to 16 -> 8 khz */
@@ -164,6 +163,7 @@
     /******************************************************************************
     * 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 */
@@ -176,27 +176,31 @@
         silk_assert( basis_ptr >= frame_4kHz );
         silk_assert( basis_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz );
 
-        /* Calculate first vector products before loop */
-        cross_corr = silk_inner_product_FLP( target_ptr, basis_ptr, sf_length_8kHz );
-        normalizer = silk_energy_FLP( basis_ptr, sf_length_8kHz ) + sf_length_8kHz * 4000.0f;
+        celt_pitch_xcorr( target_ptr, target_ptr-max_lag_4kHz, xcorr, sf_length_8kHz, max_lag_4kHz - min_lag_4kHz + 1 );
 
-        C[ 0 ][ min_lag_4kHz ] += (silk_float)(cross_corr / sqrt(normalizer));
+        /* 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++) {
+        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 = silk_inner_product_FLP(target_ptr, basis_ptr, sf_length_8kHz);
+            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)(cross_corr / sqrt( normalizer ));
+            C[ 0 ][ d ] += (silk_float)( 2 * cross_corr / normalizer );
         }
         /* Update target pointer */
         target_ptr += sf_length_8kHz;
@@ -214,13 +218,7 @@
 
     /* Escape if correlation is very low already here */
     Cmax = C[ 0 ][ min_lag_4kHz ];
-    target_ptr = &frame_4kHz[ silk_SMULBB( sf_length_4kHz, nb_subfr ) ];
-    energy = 1000.0f;
-    for( i = 0; i < silk_LSHIFT( sf_length_4kHz, 2 ); i++ ) {
-        energy += target_ptr[i] * (double)target_ptr[i];
-    }
-    threshold = Cmax * Cmax;
-    if( energy / 16.0f > threshold ) {
+    if( Cmax < 0.2f ) {
         silk_memset( pitch_out, 0, nb_subfr * sizeof( opus_int ) );
         *LTPCorr      = 0.0f;
         *lagIndex     = 0;
@@ -287,14 +285,14 @@
         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 );
+        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 );
-            energy     = silk_energy_FLP( basis_ptr, sf_length_8kHz );
             if( cross_corr > 0.0f ) {
-                C[ k ][ d ] = (silk_float)(cross_corr * cross_corr / (energy * energy_tmp + eps));
+                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;
             }
@@ -317,7 +315,7 @@
         } else if( Fs_kHz == 16 ) {
             prevLag = silk_RSHIFT( prevLag, 1 );
         }
-        prevLag_log2 = silk_log2((silk_float)prevLag);
+        prevLag_log2 = silk_log2( (silk_float)prevLag );
     } else {
         prevLag_log2 = 0;
     }
@@ -356,23 +354,20 @@
                 CBimax_new = i;
             }
         }
-        CCmax_new = silk_max_float(CCmax_new, 0.0f); /* To avoid taking square root of negative number later */
-        CCmax_new_b = CCmax_new;
 
         /* Bias towards shorter lags */
-        lag_log2 = silk_log2((silk_float)d);
-        CCmax_new_b -= PE_SHORTLAG_BIAS * nb_subfr * lag_log2;
+        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);
+            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 * search_thres2    &&  /* Correlation needs to be high enough to be voiced */
-            silk_CB_lags_stage2[ 0 ][ CBimax_new ] <= min_lag_8kHz      /* Lag must be in range                             */
+        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;
@@ -390,6 +385,10 @@
         return 1;
     }
 
+    /* Output normalized correlation */
+    *LTPCorr = (silk_float)( CCmax / nb_subfr );
+    silk_assert( *LTPCorr >= 0.0f );
+
     if( Fs_kHz > 8 ) {
         /* Search in original signal */
 
@@ -406,8 +405,6 @@
         end_lag   = silk_min_int( lag + 2, max_lag );
         lag_new   = lag;                                    /* to avoid undefined lag */
         CBimax    = 0;                                      /* to avoid undefined lag */
-        silk_assert( CCmax >= 0.0f );
-        *LTPCorr = (silk_float)sqrt( CCmax / nb_subfr );    /* Output normalized correlation */
 
         CCmax = -1000.0f;
 
@@ -430,25 +427,25 @@
             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 = eps;
+                energy = energy_tmp;
                 for( k = 0; k < nb_subfr; k++ ) {
-                    energy     +=   energies_st3[ k ][ j ][ lag_counter ];
                     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)(cross_corr * cross_corr / energy);
+                    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
-                   ) {
+                if( CCmax_new > CCmax && ( d + (opus_int)silk_CB_lags_stage3[ 0 ][ j ] ) <= max_lag ) {
                     CCmax   = CCmax_new;
                     lag_new = d;
                     CBimax  = j;
@@ -464,12 +461,10 @@
         *lagIndex = (opus_int16)( lag_new - min_lag );
         *contourIndex = (opus_int8)CBimax;
     } else {        /* Fs_kHz == 8 */
-        /* Save Lags and correlation */
-        silk_assert( CCmax >= 0.0f );
-        *LTPCorr = (silk_float)sqrt( CCmax / nb_subfr ); /* Output normalized correlation */
+        /* 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 * Fs_kHz );
+            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;
@@ -479,6 +474,19 @@
     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                                            */
@@ -487,24 +495,12 @@
     opus_int            nb_subfr,           /* I number of subframes                                            */
     opus_int            complexity          /* I Complexity setting                                             */
 )
-    /***********************************************************************
-     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.
-     **********************************************************************/
 {
     const silk_float *target_ptr, *basis_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 );
@@ -530,10 +526,12 @@
         /* 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 );
         for( j = lag_low; j <= lag_high; j++ ) {
             basis_ptr = target_ptr - ( start_lag + j );
             silk_assert( lag_counter < SCRATCH_SIZE );
-            scratch_mem[ lag_counter ] = (silk_float)silk_inner_product_FLP( target_ptr, basis_ptr, sf_length );
+            scratch_mem[ lag_counter ] = xcorr[ lag_high - j ];
             lag_counter++;
         }
 
@@ -552,6 +550,10 @@
     }
 }
 
+/********************************************************************/
+/* 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                                            */
@@ -560,10 +562,6 @@
     opus_int            nb_subfr,           /* I number of subframes                                            */
     opus_int            complexity          /* I Complexity setting                                             */
 )
-/****************************************************************
-Calculate the energies for first two subframes. The energies are
-calculated recursively.
-****************************************************************/
 {
     const silk_float *target_ptr, *basis_ptr;
     double    energy;
diff --git a/silk/float/prefilter_FLP.c b/silk/float/prefilter_FLP.c
index d6c8439..a3f81c9 100644
--- a/silk/float/prefilter_FLP.c
+++ b/silk/float/prefilter_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/process_gains_FLP.c b/silk/float/process_gains_FLP.c
index d572a4c..c0da0da 100644
--- a/silk/float/process_gains_FLP.c
+++ b/silk/float/process_gains_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/regularize_correlations_FLP.c b/silk/float/regularize_correlations_FLP.c
index f568463..df46126 100644
--- a/silk/float/regularize_correlations_FLP.c
+++ b/silk/float/regularize_correlations_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/residual_energy_FLP.c b/silk/float/residual_energy_FLP.c
index e65457a..b2e03a8 100644
--- a/silk/float/residual_energy_FLP.c
+++ b/silk/float/residual_energy_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/scale_copy_vector_FLP.c b/silk/float/scale_copy_vector_FLP.c
index 988795a..20db32b 100644
--- a/silk/float/scale_copy_vector_FLP.c
+++ b/silk/float/scale_copy_vector_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/scale_vector_FLP.c b/silk/float/scale_vector_FLP.c
index 387eb4b..108fdcb 100644
--- a/silk/float/scale_vector_FLP.c
+++ b/silk/float/scale_vector_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/schur_FLP.c b/silk/float/schur_FLP.c
index 90c3a18..ee436f8 100644
--- a/silk/float/schur_FLP.c
+++ b/silk/float/schur_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/solve_LS_FLP.c b/silk/float/solve_LS_FLP.c
index a4bb052..0eda65a 100644
--- a/silk/float/solve_LS_FLP.c
+++ b/silk/float/solve_LS_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/sort_FLP.c b/silk/float/sort_FLP.c
index e290c38..f08d759 100644
--- a/silk/float/sort_FLP.c
+++ b/silk/float/sort_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/structs_FLP.h b/silk/float/structs_FLP.h
index c71e7bc..bb529e7 100644
--- a/silk/float/structs_FLP.h
+++ b/silk/float/structs_FLP.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/warped_autocorrelation_FLP.c b/silk/float/warped_autocorrelation_FLP.c
index e9ecc2a..542414f 100644
--- a/silk/float/warped_autocorrelation_FLP.c
+++ b/silk/float/warped_autocorrelation_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/float/wrappers_FLP.c b/silk/float/wrappers_FLP.c
index 4259e90..0d33d9e 100644
--- a/silk/float/wrappers_FLP.c
+++ b/silk/float/wrappers_FLP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/gain_quant.c b/silk/gain_quant.c
index b2f7373..64ccd06 100644
--- a/silk/gain_quant.c
+++ b/silk/gain_quant.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/init_decoder.c b/silk/init_decoder.c
index 4783489..f887c67 100644
--- a/silk/init_decoder.c
+++ b/silk/init_decoder.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/init_encoder.c b/silk/init_encoder.c
index fe3fe96..7a4d918 100644
--- a/silk/init_encoder.c
+++ b/silk/init_encoder.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/inner_prod_aligned.c b/silk/inner_prod_aligned.c
index fe20a2b..257ae9e 100644
--- a/silk/inner_prod_aligned.c
+++ b/silk/inner_prod_aligned.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/interpolate.c b/silk/interpolate.c
index 226488b..1bd8ca4 100644
--- a/silk/interpolate.c
+++ b/silk/interpolate.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/lin2log.c b/silk/lin2log.c
index 212b670..d4fe515 100644
--- a/silk/lin2log.c
+++ b/silk/lin2log.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/log2lin.c b/silk/log2lin.c
index 33a19ad..07d97a9 100644
--- a/silk/log2lin.c
+++ b/silk/log2lin.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/macros.h b/silk/macros.h
index 2612fc7..35d63fa 100644
--- a/silk/macros.h
+++ b/silk/macros.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -76,59 +76,36 @@
                                         (( (a) & ((b)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a)-(b)) :    \
                                         ((((a)^0x80000000) & (b)  & 0x80000000) ? silk_int32_MAX : (a)-(b)) )
 
+#include "ecintrin.h"
+
 static inline opus_int32 silk_CLZ16(opus_int16 in16)
 {
-    opus_int32 out32 = 0;
-    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;
-    }
+    return 32 - EC_ILOG(in16<<16|0x8000);
 }
 
 static inline opus_int32 silk_CLZ32(opus_int32 in32)
 {
-    /* test highest 16 bits and convert to opus_int16 */
-    if( in32 & 0xFFFF0000 ) {
-        return silk_CLZ16((opus_int16)(in32 >> 16));
-    } else {
-        return silk_CLZ16((opus_int16)in32) + 16;
-    }
+    return in32 ? 32 - EC_ILOG(in32) : 32;
 }
 
 /* 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)))
+#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)))
+#   define matrix_c_ptr(Matrix_base_adr, row, column, M) \
+    (*((Matrix_base_adr) + ((row)+(M)*(column))))
+#endif
+
+#ifdef ARMv4_ASM
+#include "arm/macros_armv4.h"
+#endif
+
+#ifdef ARMv5E_ASM
+#include "arm/macros_armv5e.h"
 #endif
 
 #endif /* SILK_MACROS_H */
diff --git a/silk/main.h b/silk/main.h
index 32675f6..8676316 100644
--- a/silk/main.h
+++ b/silk/main.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/pitch_est_defines.h b/silk/pitch_est_defines.h
index 0b6770e..e1e4b5d 100644
--- a/silk/pitch_est_defines.h
+++ b/silk/pitch_est_defines.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/pitch_est_tables.c b/silk/pitch_est_tables.c
index 7b139ed..81a8bac 100644
--- a/silk/pitch_est_tables.c
+++ b/silk/pitch_est_tables.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/process_NLSFs.c b/silk/process_NLSFs.c
index 34ce791..c27cf03 100644
--- a/silk/process_NLSFs.c
+++ b/silk/process_NLSFs.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/quant_LTP_gains.c b/silk/quant_LTP_gains.c
index f73c0f5..43b43cb 100644
--- a/silk/quant_LTP_gains.c
+++ b/silk/quant_LTP_gains.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler.c b/silk/resampler.c
index 7e58332..374fbb3 100644
--- a/silk/resampler.c
+++ b/silk/resampler.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler_down2.c b/silk/resampler_down2.c
index 21d1199..cec3634 100644
--- a/silk/resampler_down2.c
+++ b/silk/resampler_down2.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -35,8 +35,8 @@
 /* Downsample by a factor 2 */
 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_int16                  *out,               /* O    Output signal [ floor(len/2) ]                              */
+    const opus_int16            *in,                /* I    Input signal [ len ]                                        */
     opus_int32                  inLen               /* I    Number of input samples                                     */
 )
 {
diff --git a/silk/resampler_down2_3.c b/silk/resampler_down2_3.c
index fe5b671..4342614 100644
--- a/silk/resampler_down2_3.c
+++ b/silk/resampler_down2_3.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -31,6 +31,7 @@
 
 #include "SigProc_FIX.h"
 #include "resampler_private.h"
+#include "stack_alloc.h"
 
 #define ORDER_FIR                   4
 
@@ -43,8 +44,11 @@
 )
 {
     opus_int32 nSamplesIn, counter, res_Q6;
-    opus_int32 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + ORDER_FIR ];
+    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 ) );
@@ -95,4 +99,5 @@
 
     /* 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/silk/resampler_private.h b/silk/resampler_private.h
index 45d342c..422a7d9 100644
--- a/silk/resampler_private.h
+++ b/silk/resampler_private.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler_private_AR2.c b/silk/resampler_private_AR2.c
index d069f2d..5fff237 100644
--- a/silk/resampler_private_AR2.c
+++ b/silk/resampler_private_AR2.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler_private_IIR_FIR.c b/silk/resampler_private_IIR_FIR.c
index d9e42ca..4cc8f3b 100644
--- a/silk/resampler_private_IIR_FIR.c
+++ b/silk/resampler_private_IIR_FIR.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -31,6 +31,7 @@
 
 #include "SigProc_FIX.h"
 #include "resampler_private.h"
+#include "stack_alloc.h"
 
 static inline opus_int16 *silk_resampler_private_IIR_FIR_INTERPOL(
     opus_int16  *out,
@@ -71,10 +72,13 @@
     silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
     opus_int32 nSamplesIn;
     opus_int32 max_index_Q16, index_increment_Q16;
-    opus_int16 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + RESAMPLER_ORDER_FIR_12 ];
+    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, RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
+    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;
@@ -91,13 +95,13 @@
 
         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_int32 ) );
+            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, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
+    silk_memcpy( S->sFIR.i16, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
+    RESTORE_STACK;
 }
-
diff --git a/silk/resampler_private_down_FIR.c b/silk/resampler_private_down_FIR.c
index 5d24564..73b1c40 100644
--- a/silk/resampler_private_down_FIR.c
+++ b/silk/resampler_private_down_FIR.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -31,6 +31,7 @@
 
 #include "SigProc_FIX.h"
 #include "resampler_private.h"
+#include "stack_alloc.h"
 
 static inline opus_int16 *silk_resampler_private_down_FIR_INTERPOL(
     opus_int16          *out,
@@ -151,11 +152,14 @@
     silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
     opus_int32 nSamplesIn;
     opus_int32 max_index_Q16, index_increment_Q16;
-    opus_int32 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + SILK_RESAMPLER_MAX_FIR_ORDER ];
+    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, S->FIR_Order * sizeof( opus_int32 ) );
+    silk_memcpy( buf, S->sFIR.i32, S->FIR_Order * sizeof( opus_int32 ) );
 
     FIR_Coefs = &S->Coefs[ 2 ];
 
@@ -185,5 +189,6 @@
     }
 
     /* Copy last part of filtered signal to the state for the next call */
-    silk_memcpy( S->sFIR, &buf[ nSamplesIn ], S->FIR_Order * sizeof( opus_int32 ) );
+    silk_memcpy( S->sFIR.i32, &buf[ nSamplesIn ], S->FIR_Order * sizeof( opus_int32 ) );
+    RESTORE_STACK;
 }
diff --git a/silk/resampler_private_up2_HQ.c b/silk/resampler_private_up2_HQ.c
index 9e6dfc9..c7ec8de 100644
--- a/silk/resampler_private_up2_HQ.c
+++ b/silk/resampler_private_up2_HQ.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler_rom.c b/silk/resampler_rom.c
index b50af2e..2d50270 100644
--- a/silk/resampler_rom.c
+++ b/silk/resampler_rom.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler_rom.h b/silk/resampler_rom.h
index 473b24a..490b338 100644
--- a/silk/resampler_rom.h
+++ b/silk/resampler_rom.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/resampler_structs.h b/silk/resampler_structs.h
index 4c28bd0..9e9457d 100644
--- a/silk/resampler_structs.h
+++ b/silk/resampler_structs.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -37,7 +37,10 @@
 
 typedef struct _silk_resampler_state_struct{
     opus_int32       sIIR[ SILK_RESAMPLER_MAX_IIR_ORDER ]; /* this must be the first element of this struct */
-    opus_int32       sFIR[ SILK_RESAMPLER_MAX_FIR_ORDER ];
+    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;
diff --git a/silk/shell_coder.c b/silk/shell_coder.c
index 32d0012..9fe5e40 100644
--- a/silk/shell_coder.c
+++ b/silk/shell_coder.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/sigm_Q15.c b/silk/sigm_Q15.c
index cf5af6b..3c507d2 100644
--- a/silk/sigm_Q15.c
+++ b/silk/sigm_Q15.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/sort.c b/silk/sort.c
index a4072ec..8670dbd 100644
--- a/silk/sort.c
+++ b/silk/sort.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/stereo_LR_to_MS.c b/silk/stereo_LR_to_MS.c
index 6a680e0..42906e6 100644
--- a/silk/stereo_LR_to_MS.c
+++ b/silk/stereo_LR_to_MS.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -30,6 +30,7 @@
 #endif
 
 #include "main.h"
+#include "stack_alloc.h"
 
 /* Convert Left/Right stereo signal to adaptive Mid/Side representation */
 void silk_stereo_LR_to_MS(
@@ -49,11 +50,15 @@
     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;
-    opus_int16 side[ MAX_FRAME_LENGTH + 2 ];
-    opus_int16 LP_mid[  MAX_FRAME_LENGTH ], HP_mid[  MAX_FRAME_LENGTH ];
-    opus_int16 LP_side[ MAX_FRAME_LENGTH ], HP_side[ MAX_FRAME_LENGTH ];
+    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 ];
@@ -69,6 +74,8 @@
     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 ] + mid[ n + 2 ], mid[ n + 1 ], 1 ), 2 );
         LP_mid[ n ] = sum;
@@ -76,6 +83,8 @@
     }
 
     /* 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 ] + side[ n + 2 ], side[ n + 1 ], 1 ), 2 );
         LP_side[ n ] = sum;
@@ -216,4 +225,5 @@
     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/silk/stereo_MS_to_LR.c b/silk/stereo_MS_to_LR.c
index 2351587..62521a4 100644
--- a/silk/stereo_MS_to_LR.c
+++ b/silk/stereo_MS_to_LR.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/stereo_decode_pred.c b/silk/stereo_decode_pred.c
index 026aa7a..56ba392 100644
--- a/silk/stereo_decode_pred.c
+++ b/silk/stereo_decode_pred.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/stereo_encode_pred.c b/silk/stereo_encode_pred.c
index 3cffd36..e6dd195 100644
--- a/silk/stereo_encode_pred.c
+++ b/silk/stereo_encode_pred.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/stereo_find_predictor.c b/silk/stereo_find_predictor.c
index aec58da..e30e90b 100644
--- a/silk/stereo_find_predictor.c
+++ b/silk/stereo_find_predictor.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/stereo_quant_pred.c b/silk/stereo_quant_pred.c
index df97c9f..d4ced6c 100644
--- a/silk/stereo_quant_pred.c
+++ b/silk/stereo_quant_pred.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/structs.h b/silk/structs.h
index 5d37f66..4ccd0c1 100644
--- a/silk/structs.h
+++ b/silk/structs.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/sum_sqr_shift.c b/silk/sum_sqr_shift.c
index 2eaf77b..12514c9 100644
--- a/silk/sum_sqr_shift.c
+++ b/silk/sum_sqr_shift.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/table_LSF_cos.c b/silk/table_LSF_cos.c
index 710537f..ec9dc63 100644
--- a/silk/table_LSF_cos.c
+++ b/silk/table_LSF_cos.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables.h b/silk/tables.h
index 072b792..18bf9f2 100644
--- a/silk/tables.h
+++ b/silk/tables.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_LTP.c b/silk/tables_LTP.c
index dd1fb55..b0cff44 100644
--- a/silk/tables_LTP.c
+++ b/silk/tables_LTP.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_NLSF_CB_NB_MB.c b/silk/tables_NLSF_CB_NB_MB.c
index 7548052..8c59d20 100644
--- a/silk/tables_NLSF_CB_NB_MB.c
+++ b/silk/tables_NLSF_CB_NB_MB.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_NLSF_CB_WB.c b/silk/tables_NLSF_CB_WB.c
index 3d6052e..50af87e 100644
--- a/silk/tables_NLSF_CB_WB.c
+++ b/silk/tables_NLSF_CB_WB.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_gain.c b/silk/tables_gain.c
index fccef82..37e41d8 100644
--- a/silk/tables_gain.c
+++ b/silk/tables_gain.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_other.c b/silk/tables_other.c
index 3dc68d4..398686b 100644
--- a/silk/tables_other.c
+++ b/silk/tables_other.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_pitch_lag.c b/silk/tables_pitch_lag.c
index 819b0ab..e80cc59 100644
--- a/silk/tables_pitch_lag.c
+++ b/silk/tables_pitch_lag.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tables_pulses_per_block.c b/silk/tables_pulses_per_block.c
index 521e6ff..c7c01c8 100644
--- a/silk/tables_pulses_per_block.c
+++ b/silk/tables_pulses_per_block.c
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/tuning_parameters.h b/silk/tuning_parameters.h
index a26de4d..bf4f63f 100644
--- a/silk/tuning_parameters.h
+++ b/silk/tuning_parameters.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk/typedef.h b/silk/typedef.h
index da98123..6394cde 100644
--- a/silk/typedef.h
+++ b/silk/typedef.h
@@ -8,11 +8,11 @@
 - Redistributions in binary form must reproduce the above copyright
 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 
+- 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
diff --git a/silk_headers.mk b/silk_headers.mk
index 45c6985..316cd4b 100644
--- a/silk_headers.mk
+++ b/silk_headers.mk
@@ -19,6 +19,10 @@
 silk/resampler_rom.h \
 silk/resampler_structs.h \
 silk/SigProc_FIX.h \
+silk/arm/macros_armv4.h \
+silk/arm/macros_armv5e.h \
+silk/arm/SigProc_FIX_armv4.h \
+silk/arm/SigProc_FIX_armv5e.h \
 silk/fixed/main_FIX.h \
 silk/fixed/structs_FIX.h \
 silk/float/main_FLP.h \
diff --git a/src/analysis.c b/src/analysis.c
new file mode 100644
index 0000000..53247df
--- /dev/null
+++ b/src/analysis.c
@@ -0,0 +1,647 @@
+/* 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
+
+#include "kiss_fft.h"
+#include "celt.h"
+#include "modes.h"
+#include "arch.h"
+#include "quant_bands.h"
+#include <stdio.h>
+#include "analysis.h"
+#include "mlp.h"
+#include "stack_alloc.h"
+
+extern const MLP net;
+
+#ifndef M_PI
+#define M_PI 3.141592653
+#endif
+
+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] = {
+       2,  4,  6,  8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 68, 80, 96, 120
+};
+
+static const int extra_bands[NB_TOT_BANDS+1] = {
+      1, 2,  4,  6,  8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 68, 80, 96, 120, 160, 200
+};
+
+/*static const float tweight[NB_TBANDS+1] = {
+      .3, .4, .5, .6, .7, .8, .9, 1., 1., 1., 1., 1., 1., 1., .8, .7, .6, .5
+};*/
+
+#define NB_TONAL_SKIP_BANDS 9
+
+#define cA 0.43157974f
+#define cB 0.67848403f
+#define cC 0.08595542f
+#define cE ((float)M_PI/2)
+static inline float fast_atan2f(float y, float x) {
+   float x2, y2;
+   /* Should avoid underflow on the values we'll get */
+   if (ABS16(x)+ABS16(y)<1e-9f)
+   {
+      x*=1e12f;
+      y*=1e12f;
+   }
+   x2 = x*x;
+   y2 = y*y;
+   if(x2<y2){
+      float den = (y2 + cB*x2) * (y2 + cC*x2);
+      if (den!=0)
+         return -x*y*(y2 + cA*x2) / den + (y<0 ? -cE : cE);
+      else
+         return (y<0 ? -cE : cE);
+   }else{
+      float den = (x2 + cB*y2) * (x2 + cC*y2);
+      if (den!=0)
+         return  x*y*(x2 + cA*y2) / den + (y<0 ? -cE : cE) - (x*y<0 ? -cE : cE);
+      else
+         return (y<0 ? -cE : cE) - (x*y<0 ? -cE : cE);
+   }
+}
+
+void tonality_get_info(TonalityAnalysisState *tonal, AnalysisInfo *info_out, int len)
+{
+   int pos;
+   int curr_lookahead;
+   float psum;
+   int i;
+
+   pos = tonal->read_pos;
+   curr_lookahead = tonal->write_pos-tonal->read_pos;
+   if (curr_lookahead<0)
+      curr_lookahead += DETECT_SIZE;
+
+   if (len > 480 && 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);
+   tonal->read_subframe += len/120;
+   while (tonal->read_subframe>=4)
+   {
+      tonal->read_subframe -= 4;
+      tonal->read_pos++;
+   }
+   if (tonal->read_pos>=DETECT_SIZE)
+      tonal->read_pos-=DETECT_SIZE;
+
+   /* Compensate for the delay in the features themselves.
+      FIXME: Need a better estimate the 10 I just made up */
+   curr_lookahead = IMAX(curr_lookahead-10, 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\n", psum, info_out->music_prob, info_out->tonality);*/
+
+   info_out->music_prob = psum;
+}
+
+void tonality_analysis(TonalityAnalysisState *tonal, AnalysisInfo *info_out, 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;
+    SAVE_STACK;
+
+    tonal->last_transition++;
+    alpha = 1.f/IMIN(20, 1+tonal->count);
+    alphaE = 1.f/IMIN(50, 1+tonal->count);
+    alphaE2 = 1.f/IMIN(1000, 1+tonal->count);
+
+    if (tonal->count<4)
+       tonal->music_prob = .5;
+    kfft = celt_mode->mdct.kfft[0];
+    if (tonal->count==0)
+       tonal->mem_fill = 240;
+    downmix(x, &tonal->inmem[tonal->mem_fill], IMIN(len, ANALYSIS_BUF_SIZE-tonal->mem_fill), offset, c1, c2, C);
+    if (tonal->mem_fill+len < ANALYSIS_BUF_SIZE)
+    {
+       tonal->mem_fill += len;
+       /* Don't have enough to update the analysis */
+       RESTORE_STACK;
+       return;
+    }
+    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 = w*tonal->inmem[i];
+       in[i].i = w*tonal->inmem[N2+i];
+       in[N-i-1].r = w*tonal->inmem[N-i-1];
+       in[N-i-1].i = 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);
+    downmix(x, &tonal->inmem[240], remaining, offset+ANALYSIS_BUF_SIZE-tonal->mem_fill, c1, c2, C);
+    tonal->mem_fill = 240 + remaining;
+    opus_fft(kfft, in, out);
+
+    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 = out[i].r+out[N-i].r;
+       X1i = out[i].i-out[N-i].i;
+       X2r = out[i].i+out[N-i].i;
+       X2i = 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)floor(.5+d2_angle);
+       noisiness[i] = ABS16(mod1);
+       mod1 *= mod1;
+       mod1 *= mod1;
+
+       mod2 = d2_angle2 - (float)floor(.5+d2_angle2);
+       noisiness[i] += ABS16(mod2);
+       mod2 *= mod2;
+       mod2 *= mod2;
+
+       avg_mod = .25f*(d2A[i]+2.f*mod1+mod2);
+       tonality[i] = 1.f/(1.f+40.f*16.f*pi4*avg_mod)-.015f;
+
+       A[i] = angle2;
+       dA[i] = d_angle2;
+       d2A[i] = mod2;
+    }
+
+    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;
+    bandwidth_mask = 0;
+    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;
+#ifdef FIXED_POINT
+          /* FIXME: It's probably best to change the BFCC filter initial state instead */
+          binE *= 5.55e-17f;
+#endif
+          E += binE;
+          tE += binE*tonality[i];
+          nE += binE*2.f*(.5f-noisiness[i]);
+       }
+       tonal->E[tonal->E_count][b] = E;
+       frame_noisiness += nE/(1e-15f+E);
+
+       frame_loudness += sqrt(E+1e-10f);
+       logE[b] = (float)log(E+1e-10f);
+       tonal->lowE[b] = MIN32(logE[b], tonal->lowE[b]+.01f);
+       tonal->highE[b] = MAX32(logE[b], tonal->highE[b]-.1f);
+       if (tonal->highE[b] < tonal->lowE[b]+1.f)
+       {
+          tonal->highE[b]+=.5f;
+          tonal->lowE[b]-=.5f;
+       }
+       relativeE += (logE[b]-tonal->lowE[b])/(1e-15+tonal->highE[b]-tonal->lowE[b]);
+
+       L1=L2=0;
+       for (i=0;i<NB_FRAMES;i++)
+       {
+          L1 += sqrt(tonal->E[i][b]);
+          L2 += tonal->E[i][b];
+       }
+
+       stationarity = MIN16(0.99f,L1/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-15+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];
+    }
+
+    bandwidth_mask = 0;
+    bandwidth = 0;
+    maxE = 0;
+    noise_floor = 5.7e-4f/(1<<(IMAX(0,lsb_depth-8)));
+#ifdef FIXED_POINT
+    noise_floor *= 1<<(15+SIG_SHIFT);
+#endif
+    noise_floor *= noise_floor;
+    for (b=0;b<NB_TOT_BANDS;b++)
+    {
+       float E=0;
+       int band_start, band_end;
+       /* Keep a margin of 300 Hz for aliasing */
+       band_start = extra_bands[b];
+       band_end = extra_bands[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;
+       }
+       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
+       */
+       if (E>.1*bandwidth_mask && E*1e9f > maxE && E > noise_floor*(band_end-band_start))
+          bandwidth = b;
+    }
+    if (tonal->count<=2)
+       bandwidth = 20;
+    frame_loudness = 20*(float)log10(frame_loudness);
+    tonal->Etracker = MAX32(tonal->Etracker-.03f, 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;
+    }
+
+    frame_stationarity /= NB_TBANDS;
+    relativeE /= NB_TBANDS;
+    if (tonal->count<10)
+       relativeE = .5;
+    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++;
+    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<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] = sqrt(tonal->std[i]);
+    features[20] = info->tonality;
+    features[21] = info->activity;
+    features[22] = frame_stationarity;
+    features[23] = info->tonality_slope;
+    features[24] = tonal->lowECount;
+
+#ifndef DISABLE_FLOAT_API
+    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;
+    /* Consider that silence has a 50-50 probability. */
+    frame_probs[0] = frame_probs[1]*frame_probs[0] + (1-frame_probs[1])*.5f;
+
+    /*printf("%f %f ", 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;
+
+       /* One transition every 3 minutes of active audio */
+       tau = .00005f*frame_probs[1];
+       beta = .05f;
+       if (1) {
+          /* Adapt beta based on how "unexpected" the new prob is */
+          float p, q;
+          p = MAX16(.05f,MIN16(.95f,frame_probs[0]));
+          q = MAX16(.05f,MIN16(.95f,tonal->music_prob));
+          beta = .01f+.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;
+
+       /* 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)
+       {
+          tonal->pspeech[0]=.5;
+          tonal->pmusic [0]=.5;
+       }
+       /* 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);
+          }
+       } else {
+          if (tonal->music_confidence_count==0)
+             tonal->music_confidence = .9f;
+          if (tonal->speech_confidence_count==0)
+             tonal->speech_confidence = .1f;
+       }
+       psum = MAX16(tonal->speech_confidence, MIN16(tonal->music_confidence, psum));
+    }
+    if (tonal->last_music != (tonal->music_prob>.5f))
+       tonal->last_transition=0;
+    tonal->last_music = tonal->music_prob>.5f;
+#else
+    info->music_prob = 0;
+#endif
+    /*for (i=0;i<25;i++)
+       printf("%f ", features[i]);
+    printf("\n");*/
+
+    info->bandwidth = bandwidth;
+    /*printf("%d %d\n", info->bandwidth, info->opus_bandwidth);*/
+    info->noisiness = frame_noisiness;
+    info->valid = 1;
+    if (info_out!=NULL)
+       OPUS_COPY(info_out, info, 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;
+
+   if (analysis_pcm != NULL)
+   {
+      /* Avoid overflow/wrap-around of the analysis buffer */
+      analysis_frame_size = IMIN((DETECT_SIZE-5)*Fs/100, analysis_frame_size);
+
+      pcm_len = analysis_frame_size - analysis->analysis_offset;
+      offset = analysis->analysis_offset;
+      do {
+         tonality_analysis(analysis, NULL, celt_mode, analysis_pcm, IMIN(480, pcm_len), offset, c1, c2, C, lsb_depth, downmix);
+         offset += 480;
+         pcm_len -= 480;
+      } while (pcm_len>0);
+      analysis->analysis_offset = analysis_frame_size;
+
+      analysis->analysis_offset -= frame_size;
+   }
+
+   analysis_info->valid = 0;
+   tonality_get_info(analysis, analysis_info, frame_size);
+}
diff --git a/src/analysis.h b/src/analysis.h
new file mode 100644
index 0000000..cf37792
--- /dev/null
+++ b/src/analysis.h
@@ -0,0 +1,90 @@
+/* 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 NB_TOT_BANDS 21
+#define ANALYSIS_BUF_SIZE 720 /* 15 ms at 48 kHz */
+
+#define DETECT_SIZE 200
+
+typedef struct {
+   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;
+   float E[NB_FRAMES][NB_TBANDS];
+   float lowE[NB_TBANDS];
+   float highE[NB_TBANDS];
+   float meanE[NB_TOT_BANDS];
+   float mem[32];
+   float cmean[8];
+   float std[9];
+   float music_prob;
+   float Etracker;
+   float lowECount;
+   int E_count;
+   int last_music;
+   int last_transition;
+   int count;
+   opus_val32   subframe_mem[3];
+   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;
+   AnalysisInfo info[DETECT_SIZE];
+} TonalityAnalysisState;
+
+void tonality_analysis(TonalityAnalysisState *tonal, AnalysisInfo *info,
+     const CELTMode *celt_mode, const void *x, int len, int offset, int c1, int c2, int C, int lsb_depth, downmix_func downmix);
+
+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/src/mlp.c b/src/mlp.c
new file mode 100644
index 0000000..73b1d31
--- /dev/null
+++ b/src/mlp.c
@@ -0,0 +1,136 @@
+/* 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 <math.h>
+#include "mlp.h"
+#include "arch.h"
+#include "tansig_table.h"
+#define MAX_NEURONS 100
+
+#if 0
+static 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 inline float tansig_approx(float x)
+{
+	int i;
+	float y, dy;
+	float sign=1;
+    if (x>=8)
+        return 1;
+    if (x<=-8)
+        return -1;
+	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/src/mlp.h b/src/mlp.h
new file mode 100644
index 0000000..86c8e06
--- /dev/null
+++ b/src/mlp.h
@@ -0,0 +1,41 @@
+/* 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;
+
+void mlp_process(const MLP *m, const float *in, float *out);
+
+#endif /* _MLP_H_ */
diff --git a/src/mlp_data.c b/src/mlp_data.c
new file mode 100644
index 0000000..401c4c0
--- /dev/null
+++ b/src/mlp_data.c
@@ -0,0 +1,105 @@
+/* The contents of this file was automatically generated by mlp_train.c
+   It contains multi-layer perceptron (MLP) weights. */
+
+#include "mlp.h"
+
+/* RMS error was 0.138320, seed was 1361535663 */
+
+static const float weights[422] = {
+
+/* hidden layer */
+-0.0941125f, -0.302976f, -0.603555f, -0.19393f, -0.185983f,
+-0.601617f, -0.0465317f, -0.114563f, -0.103599f, -0.618938f,
+-0.317859f, -0.169949f, -0.0702885f, 0.148065f, 0.409524f,
+0.548432f, 0.367649f, -0.494393f, 0.764306f, -1.83957f,
+0.170849f, 12.786f, -1.08848f, -1.27284f, -16.2606f,
+24.1773f, -5.57454f, -0.17276f, -0.163388f, -0.224421f,
+-0.0948944f, -0.0728695f, -0.26557f, -0.100283f, -0.0515459f,
+-0.146142f, -0.120674f, -0.180655f, 0.12857f, 0.442138f,
+-0.493735f, 0.167767f, 0.206699f, -0.197567f, 0.417999f,
+1.50364f, -0.773341f, -10.0401f, 0.401872f, 2.97966f,
+15.2165f, -1.88905f, -1.19254f, 0.0285397f, -0.00405139f,
+0.0707565f, 0.00825699f, -0.0927269f, -0.010393f, -0.00428882f,
+-0.00489743f, -0.0709731f, -0.00255992f, 0.0395619f, 0.226424f,
+0.0325231f, 0.162175f, -0.100118f, 0.485789f, 0.12697f,
+0.285937f, 0.0155637f, 0.10546f, 3.05558f, 1.15059f,
+-1.00904f, -1.83088f, 3.31766f, -3.42516f, -0.119135f,
+-0.0405654f, 0.00690068f, 0.0179877f, -0.0382487f, 0.00597941f,
+-0.0183611f, 0.00190395f, -0.144322f, -0.0435671f, 0.000990594f,
+0.221087f, 0.142405f, 0.484066f, 0.404395f, 0.511955f,
+-0.237255f, 0.241742f, 0.35045f, -0.699428f, 10.3993f,
+2.6507f, -2.43459f, -4.18838f, 1.05928f, 1.71067f,
+0.00667811f, -0.0721335f, -0.0397346f, 0.0362704f, -0.11496f,
+-0.0235776f, 0.0082161f, -0.0141741f, -0.0329699f, -0.0354253f,
+0.00277404f, -0.290654f, -1.14767f, -0.319157f, -0.686544f,
+0.36897f, 0.478899f, 0.182579f, -0.411069f, 0.881104f,
+-4.60683f, 1.4697f, 0.335845f, -1.81905f, -30.1699f,
+5.55225f, 0.0019508f, -0.123576f, -0.0727332f, -0.0641597f,
+-0.0534458f, -0.108166f, -0.0937368f, -0.0697883f, -0.0275475f,
+-0.192309f, -0.110074f, 0.285375f, -0.405597f, 0.0926724f,
+-0.287881f, -0.851193f, -0.099493f, -0.233764f, -1.2852f,
+1.13611f, 3.12168f, -0.0699f, -1.86216f, 2.65292f,
+-7.31036f, 2.44776f, -0.00111802f, -0.0632786f, -0.0376296f,
+-0.149851f, 0.142963f, 0.184368f, 0.123433f, 0.0756158f,
+0.117312f, 0.0933395f, 0.0692163f, 0.0842592f, 0.0704683f,
+0.0589963f, 0.0942205f, -0.448862f, 0.0262677f, 0.270352f,
+-0.262317f, 0.172586f, 2.00227f, -0.159216f, 0.038422f,
+10.2073f, 4.15536f, -2.3407f, -0.0550265f, 0.00964792f,
+-0.141336f, 0.0274501f, 0.0343921f, -0.0487428f, 0.0950172f,
+-0.00775017f, -0.0372492f, -0.00548121f, -0.0663695f, 0.0960506f,
+-0.200008f, -0.0412827f, 0.58728f, 0.0515787f, 0.337254f,
+0.855024f, 0.668371f, -0.114904f, -3.62962f, -0.467477f,
+-0.215472f, 2.61537f, 0.406117f, -1.36373f, 0.0425394f,
+0.12208f, 0.0934502f, 0.123055f, 0.0340935f, -0.142466f,
+0.035037f, -0.0490666f, 0.0733208f, 0.0576672f, 0.123984f,
+-0.0517194f, -0.253018f, 0.590565f, 0.145849f, 0.315185f,
+0.221534f, -0.149081f, 0.216161f, -0.349575f, 24.5664f,
+-0.994196f, 0.614289f, -18.7905f, -2.83277f, -0.716801f,
+-0.347201f, 0.479515f, -0.246027f, 0.0758683f, 0.137293f,
+-0.17781f, 0.118751f, -0.00108329f, -0.237334f, 0.355732f,
+-0.12991f, -0.0547627f, -0.318576f, -0.325524f, 0.180494f,
+-0.0625604f, 0.141219f, 0.344064f, 0.37658f, -0.591772f,
+5.8427f, -0.38075f, 0.221894f, -1.41934f, -1.87943e+06f,
+1.34114f, 0.0283355f, -0.0447856f, -0.0211466f, -0.0256927f,
+0.0139618f, 0.0207934f, -0.0107666f, 0.0110969f, 0.0586069f,
+-0.0253545f, -0.0328433f, 0.11872f, -0.216943f, 0.145748f,
+0.119808f, -0.0915211f, -0.120647f, -0.0787719f, -0.143644f,
+-0.595116f, -1.152f, -1.25335f, -1.17092f, 4.34023f,
+-975268.f, -1.37033f, -0.0401123f, 0.210602f, -0.136656f,
+0.135962f, -0.0523293f, 0.0444604f, 0.0143928f, 0.00412666f,
+-0.0193003f, 0.218452f, -0.110204f, -2.02563f, 0.918238f,
+-2.45362f, 1.19542f, -0.061362f, -1.92243f, 0.308111f,
+0.49764f, 0.912356f, 0.209272f, -2.34525f, 2.19326f,
+-6.47121f, 1.69771f, -0.725123f, 0.0118929f, 0.0377944f,
+0.0554003f, 0.0226452f, -0.0704421f, -0.0300309f, 0.0122978f,
+-0.0041782f, -0.0686612f, 0.0313115f, 0.039111f, 0.364111f,
+-0.0945548f, 0.0229876f, -0.17414f, 0.329795f, 0.114714f,
+0.30022f, 0.106997f, 0.132355f, 5.79932f, 0.908058f,
+-0.905324f, -3.3561f, 0.190647f, 0.184211f, -0.673648f,
+0.231807f, -0.0586222f, 0.230752f, -0.438277f, 0.245857f,
+-0.17215f, 0.0876383f, -0.720512f, 0.162515f, 0.0170571f,
+0.101781f, 0.388477f, 1.32931f, 1.08548f, -0.936301f,
+-2.36958f, -6.71988f, -3.44376f, 2.13818f, 14.2318f,
+4.91459f, -3.09052f, -9.69191f, -0.768234f, 1.79604f,
+0.0549653f, 0.163399f, 0.0797025f, 0.0343933f, -0.0555876f,
+-0.00505673f, 0.0187258f, 0.0326628f, 0.0231486f, 0.15573f,
+0.0476223f, -0.254824f, 1.60155f, -0.801221f, 2.55496f,
+0.737629f, -1.36249f, -0.695463f, -2.44301f, -1.73188f,
+3.95279f, 1.89068f, 0.486087f, -11.3343f, 3.9416e+06f,
+
+/* output layer */
+-0.381439f, 0.12115f, -0.906927f, 2.93878f, 1.6388f,
+0.882811f, 0.874344f, 1.21726f, -0.874545f, 0.321706f,
+0.785055f, 0.946558f, -0.575066f, -3.46553f, 0.884905f,
+0.0924047f, -9.90712f, 0.391338f, 0.160103f, -2.04954f,
+4.1455f, 0.0684029f, -0.144761f, -0.285282f, 0.379244f,
+-1.1584f, -0.0277241f, -9.85f, -4.82386f, 3.71333f,
+3.87308f, 3.52558f};
+
+static const int topo[3] = {25, 15, 2};
+
+const MLP net = {
+    3,
+    topo,
+    weights
+};
diff --git a/src/mlp_train.c b/src/mlp_train.c
new file mode 100644
index 0000000..2e9568b
--- /dev/null
+++ b/src/mlp_train.c
@@ -0,0 +1,501 @@
+/* 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.
+*/
+
+
+#include "mlp_train.h"
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <semaphore.h>
+#include <pthread.h>
+#include <time.h>
+#include <signal.h>
+
+int stopped = 0;
+
+void handler(int sig)
+{
+	stopped = 1;
+	signal(sig, handler);
+}
+
+MLPTrain * mlp_init(int *topo, int nbLayers, float *inputs, float *outputs, int nbSamples)
+{
+	int i, j, k;
+	MLPTrain *net;
+	int inDim, outDim;
+	net = malloc(sizeof(*net));
+	net->topo = malloc(nbLayers*sizeof(net->topo[0]));
+	for (i=0;i<nbLayers;i++)
+		net->topo[i] = topo[i];
+	inDim = topo[0];
+	outDim = topo[nbLayers-1];
+	net->in_rate = malloc((inDim+1)*sizeof(net->in_rate[0]));
+	net->weights = malloc((nbLayers-1)*sizeof(net->weights));
+	net->best_weights = malloc((nbLayers-1)*sizeof(net->weights));
+	for (i=0;i<nbLayers-1;i++)
+	{
+		net->weights[i] = malloc((topo[i]+1)*topo[i+1]*sizeof(net->weights[0][0]));
+		net->best_weights[i] = malloc((topo[i]+1)*topo[i+1]*sizeof(net->weights[0][0]));
+	}
+	double inMean[inDim];
+	for (j=0;j<inDim;j++)
+	{
+		double std=0;
+		inMean[j] = 0;
+		for (i=0;i<nbSamples;i++)
+		{
+			inMean[j] += inputs[i*inDim+j];
+			std += inputs[i*inDim+j]*inputs[i*inDim+j];
+		}
+		inMean[j] /= nbSamples;
+		std /= nbSamples;
+		net->in_rate[1+j] = .5/(.0001+std);
+		std = std-inMean[j]*inMean[j];
+		if (std<.001)
+			std = .001;
+		std = 1/sqrt(inDim*std);
+		for (k=0;k<topo[1];k++)
+			net->weights[0][k*(topo[0]+1)+j+1] = randn(std);
+	}
+	net->in_rate[0] = 1;
+	for (j=0;j<topo[1];j++)
+	{
+		double sum = 0;
+		for (k=0;k<inDim;k++)
+			sum += inMean[k]*net->weights[0][j*(topo[0]+1)+k+1];
+		net->weights[0][j*(topo[0]+1)] = -sum;
+	}
+	for (j=0;j<outDim;j++)
+	{
+		double mean = 0;
+		double std;
+		for (i=0;i<nbSamples;i++)
+			mean += outputs[i*outDim+j];
+		mean /= nbSamples;
+		std = 1/sqrt(topo[nbLayers-2]);
+		net->weights[nbLayers-2][j*(topo[nbLayers-2]+1)] = mean;
+		for (k=0;k<topo[nbLayers-2];k++)
+			net->weights[nbLayers-2][j*(topo[nbLayers-2]+1)+k+1] = randn(std);
+	}
+	return net;
+}
+
+#define MAX_NEURONS 100
+#define MAX_OUT 10
+
+double compute_gradient(MLPTrain *net, float *inputs, float *outputs, int nbSamples, double *W0_grad, double *W1_grad, double *error_rate)
+{
+	int i,j;
+	int s;
+	int inDim, outDim, hiddenDim;
+	int *topo;
+	double *W0, *W1;
+	double rms=0;
+	int W0_size, W1_size;
+	double hidden[MAX_NEURONS];
+	double netOut[MAX_NEURONS];
+	double error[MAX_NEURONS];
+
+	for (i=0;i<outDim;i++)
+	   error_rate[i] = 0;
+	topo = net->topo;
+	inDim = net->topo[0];
+	hiddenDim = net->topo[1];
+	outDim = net->topo[2];
+	W0_size = (topo[0]+1)*topo[1];
+	W1_size = (topo[1]+1)*topo[2];
+	W0 = net->weights[0];
+	W1 = net->weights[1];
+	memset(W0_grad, 0, W0_size*sizeof(double));
+	memset(W1_grad, 0, W1_size*sizeof(double));
+	for (i=0;i<outDim;i++)
+		netOut[i] = outputs[i];
+	for (s=0;s<nbSamples;s++)
+	{
+		float *in, *out;
+		in = inputs+s*inDim;
+		out = outputs + s*outDim;
+		for (i=0;i<hiddenDim;i++)
+		{
+			double sum = W0[i*(inDim+1)];
+			for (j=0;j<inDim;j++)
+				sum += W0[i*(inDim+1)+j+1]*in[j];
+			hidden[i] = tansig_approx(sum);
+		}
+		for (i=0;i<outDim;i++)
+		{
+			double sum = W1[i*(hiddenDim+1)];
+			for (j=0;j<hiddenDim;j++)
+				sum += W1[i*(hiddenDim+1)+j+1]*hidden[j];
+			netOut[i] = tansig_approx(sum);
+			error[i] = out[i] - netOut[i];
+			rms += error[i]*error[i];
+			error_rate[i] += fabs(error[i])>1;
+			/*error[i] = error[i]/(1+fabs(error[i]));*/
+		}
+		/* Back-propagate error */
+		for (i=0;i<outDim;i++)
+		{
+                        float grad = 1-netOut[i]*netOut[i];
+			W1_grad[i*(hiddenDim+1)] += error[i]*grad;
+			for (j=0;j<hiddenDim;j++)
+				W1_grad[i*(hiddenDim+1)+j+1] += grad*error[i]*hidden[j];
+		}
+		for (i=0;i<hiddenDim;i++)
+		{
+			double grad;
+			grad = 0;
+			for (j=0;j<outDim;j++)
+				grad += error[j]*W1[j*(hiddenDim+1)+i+1];
+			grad *= 1-hidden[i]*hidden[i];
+			W0_grad[i*(inDim+1)] += grad;
+			for (j=0;j<inDim;j++)
+				W0_grad[i*(inDim+1)+j+1] += grad*in[j];
+		}
+	}
+	return rms;
+}
+
+#define NB_THREADS 8
+
+sem_t sem_begin[NB_THREADS];
+sem_t sem_end[NB_THREADS];
+
+struct GradientArg {
+	int id;
+	int done;
+	MLPTrain *net;
+	float *inputs;
+	float *outputs;
+	int nbSamples;
+	double *W0_grad;
+	double *W1_grad;
+	double rms;
+	double error_rate[MAX_OUT];
+};
+
+void *gradient_thread_process(void *_arg)
+{
+	int W0_size, W1_size;
+	struct GradientArg *arg = _arg;
+	int *topo = arg->net->topo;
+	W0_size = (topo[0]+1)*topo[1];
+	W1_size = (topo[1]+1)*topo[2];
+	double W0_grad[W0_size];
+	double W1_grad[W1_size];
+	arg->W0_grad = W0_grad;
+	arg->W1_grad = W1_grad;
+	while (1)
+	{
+		sem_wait(&sem_begin[arg->id]);
+		if (arg->done)
+			break;
+		arg->rms = compute_gradient(arg->net, arg->inputs, arg->outputs, arg->nbSamples, arg->W0_grad, arg->W1_grad, arg->error_rate);
+		sem_post(&sem_end[arg->id]);
+	}
+	fprintf(stderr, "done\n");
+	return NULL;
+}
+
+float mlp_train_backprop(MLPTrain *net, float *inputs, float *outputs, int nbSamples, int nbEpoch, float rate)
+{
+	int i, j;
+	int e;
+	float best_rms = 1e10;
+	int inDim, outDim, hiddenDim;
+	int *topo;
+	double *W0, *W1, *best_W0, *best_W1;
+	double *W0_old, *W1_old;
+	double *W0_old2, *W1_old2;
+	double *W0_grad, *W1_grad;
+	double *W0_oldgrad, *W1_oldgrad;
+	double *W0_rate, *W1_rate;
+	double *best_W0_rate, *best_W1_rate;
+	int W0_size, W1_size;
+	topo = net->topo;
+	W0_size = (topo[0]+1)*topo[1];
+	W1_size = (topo[1]+1)*topo[2];
+	struct GradientArg args[NB_THREADS];
+	pthread_t thread[NB_THREADS];
+	int samplePerPart = nbSamples/NB_THREADS;
+	int count_worse=0;
+	int count_retries=0;
+
+	topo = net->topo;
+	inDim = net->topo[0];
+	hiddenDim = net->topo[1];
+	outDim = net->topo[2];
+	W0 = net->weights[0];
+	W1 = net->weights[1];
+	best_W0 = net->best_weights[0];
+	best_W1 = net->best_weights[1];
+	W0_old = malloc(W0_size*sizeof(double));
+	W1_old = malloc(W1_size*sizeof(double));
+	W0_old2 = malloc(W0_size*sizeof(double));
+	W1_old2 = malloc(W1_size*sizeof(double));
+	W0_grad = malloc(W0_size*sizeof(double));
+	W1_grad = malloc(W1_size*sizeof(double));
+	W0_oldgrad = malloc(W0_size*sizeof(double));
+	W1_oldgrad = malloc(W1_size*sizeof(double));
+	W0_rate = malloc(W0_size*sizeof(double));
+	W1_rate = malloc(W1_size*sizeof(double));
+	best_W0_rate = malloc(W0_size*sizeof(double));
+	best_W1_rate = malloc(W1_size*sizeof(double));
+	memcpy(W0_old, W0, W0_size*sizeof(double));
+	memcpy(W0_old2, W0, W0_size*sizeof(double));
+	memset(W0_grad, 0, W0_size*sizeof(double));
+	memset(W0_oldgrad, 0, W0_size*sizeof(double));
+	memcpy(W1_old, W1, W1_size*sizeof(double));
+	memcpy(W1_old2, W1, W1_size*sizeof(double));
+	memset(W1_grad, 0, W1_size*sizeof(double));
+	memset(W1_oldgrad, 0, W1_size*sizeof(double));
+	
+	rate /= nbSamples;
+	for (i=0;i<hiddenDim;i++)
+		for (j=0;j<inDim+1;j++)
+			W0_rate[i*(inDim+1)+j] = rate*net->in_rate[j];
+	for (i=0;i<W1_size;i++)
+		W1_rate[i] = rate;
+	
+	for (i=0;i<NB_THREADS;i++)
+	{
+		args[i].net = net;
+		args[i].inputs = inputs+i*samplePerPart*inDim;
+		args[i].outputs = outputs+i*samplePerPart*outDim;
+		args[i].nbSamples = samplePerPart;
+		args[i].id = i;
+		args[i].done = 0;
+		sem_init(&sem_begin[i], 0, 0);
+		sem_init(&sem_end[i], 0, 0);
+		pthread_create(&thread[i], NULL, gradient_thread_process, &args[i]);
+	}
+	for (e=0;e<nbEpoch;e++)
+	{
+		double rms=0;
+		double error_rate[2] = {0,0};
+		for (i=0;i<NB_THREADS;i++)
+		{
+			sem_post(&sem_begin[i]);
+		}
+		memset(W0_grad, 0, W0_size*sizeof(double));
+		memset(W1_grad, 0, W1_size*sizeof(double));
+		for (i=0;i<NB_THREADS;i++)
+		{
+			sem_wait(&sem_end[i]);
+			rms += args[i].rms;
+			error_rate[0] += args[i].error_rate[0];
+            error_rate[1] += args[i].error_rate[1];
+			for (j=0;j<W0_size;j++)
+				W0_grad[j] += args[i].W0_grad[j];
+			for (j=0;j<W1_size;j++)
+				W1_grad[j] += args[i].W1_grad[j];
+		}
+
+		float mean_rate = 0, min_rate = 1e10;
+		rms = (rms/(outDim*nbSamples));
+		error_rate[0] = (error_rate[0]/(nbSamples));
+        error_rate[1] = (error_rate[1]/(nbSamples));
+		fprintf (stderr, "%f %f (%f %f) ", error_rate[0], error_rate[1], rms, best_rms);
+		if (rms < best_rms)
+		{
+			best_rms = rms;
+			for (i=0;i<W0_size;i++)
+			{
+				best_W0[i] = W0[i];
+				best_W0_rate[i] = W0_rate[i];
+			}
+			for (i=0;i<W1_size;i++)
+			{
+				best_W1[i] = W1[i];
+				best_W1_rate[i] = W1_rate[i];
+			}
+			count_worse=0;
+			count_retries=0;
+		} else {
+			count_worse++;
+			if (count_worse>30)
+			{
+			    count_retries++;
+				count_worse=0;
+				for (i=0;i<W0_size;i++)
+				{
+					W0[i] = best_W0[i];
+					best_W0_rate[i] *= .7;
+					if (best_W0_rate[i]<1e-15) best_W0_rate[i]=1e-15;
+					W0_rate[i] = best_W0_rate[i];
+					W0_grad[i] = 0;
+				}
+				for (i=0;i<W1_size;i++)
+				{
+					W1[i] = best_W1[i];
+					best_W1_rate[i] *= .8;
+					if (best_W1_rate[i]<1e-15) best_W1_rate[i]=1e-15;
+					W1_rate[i] = best_W1_rate[i];
+					W1_grad[i] = 0;
+				}
+			}
+		}
+		if (count_retries>10)
+		    break;
+		for (i=0;i<W0_size;i++)
+		{
+			if (W0_oldgrad[i]*W0_grad[i] > 0)
+				W0_rate[i] *= 1.01;
+			else if (W0_oldgrad[i]*W0_grad[i] < 0)
+				W0_rate[i] *= .9;
+			mean_rate += W0_rate[i];
+			if (W0_rate[i] < min_rate)
+				min_rate = W0_rate[i];
+			if (W0_rate[i] < 1e-15)
+				W0_rate[i] = 1e-15;
+			/*if (W0_rate[i] > .01)
+				W0_rate[i] = .01;*/
+			W0_oldgrad[i] = W0_grad[i];
+			W0_old2[i] = W0_old[i];
+			W0_old[i] = W0[i];
+			W0[i] += W0_grad[i]*W0_rate[i];
+		}
+		for (i=0;i<W1_size;i++)
+		{
+			if (W1_oldgrad[i]*W1_grad[i] > 0)
+				W1_rate[i] *= 1.01;
+			else if (W1_oldgrad[i]*W1_grad[i] < 0)
+				W1_rate[i] *= .9;
+			mean_rate += W1_rate[i];
+			if (W1_rate[i] < min_rate)
+				min_rate = W1_rate[i];
+			if (W1_rate[i] < 1e-15)
+				W1_rate[i] = 1e-15;
+			W1_oldgrad[i] = W1_grad[i];
+			W1_old2[i] = W1_old[i];
+			W1_old[i] = W1[i];
+			W1[i] += W1_grad[i]*W1_rate[i];
+		}
+		mean_rate /= (topo[0]+1)*topo[1] + (topo[1]+1)*topo[2];
+		fprintf (stderr, "%g %d", mean_rate, e);
+		if (count_retries)
+		    fprintf(stderr, " %d", count_retries);
+		fprintf(stderr, "\n");
+		if (stopped)
+			break;
+	}
+	for (i=0;i<NB_THREADS;i++)
+	{
+		args[i].done = 1;
+		sem_post(&sem_begin[i]);
+		pthread_join(thread[i], NULL);
+		fprintf (stderr, "joined %d\n", i);
+	}
+	free(W0_old);
+	free(W1_old);
+	free(W0_grad);
+	free(W1_grad);
+	free(W0_rate);
+	free(W1_rate);
+	return best_rms;
+}
+
+int main(int argc, char **argv)
+{
+	int i, j;
+	int nbInputs;
+	int nbOutputs;
+	int nbHidden;
+	int nbSamples;
+	int nbEpoch;
+	int nbRealInputs;
+	unsigned int seed;
+	int ret;
+	float rms;
+	float *inputs;
+	float *outputs;
+	if (argc!=6)
+	{
+		fprintf (stderr, "usage: mlp_train <inputs> <hidden> <outputs> <nb samples> <nb epoch>\n");
+		return 1;
+	}
+	nbInputs = atoi(argv[1]);
+	nbHidden = atoi(argv[2]);
+	nbOutputs = atoi(argv[3]);
+	nbSamples = atoi(argv[4]);
+	nbEpoch = atoi(argv[5]);
+	nbRealInputs = nbInputs;
+	inputs = malloc(nbInputs*nbSamples*sizeof(*inputs));
+	outputs = malloc(nbOutputs*nbSamples*sizeof(*outputs));
+	
+	seed = time(NULL);
+    /*seed = 1361480659;*/
+	fprintf (stderr, "Seed is %u\n", seed);
+	srand(seed);
+	build_tansig_table();
+	signal(SIGTERM, handler);
+	signal(SIGINT, handler);
+	signal(SIGHUP, handler);
+	for (i=0;i<nbSamples;i++)
+	{
+		for (j=0;j<nbRealInputs;j++)
+			ret = scanf(" %f", &inputs[i*nbInputs+j]);
+		for (j=0;j<nbOutputs;j++)
+			ret = scanf(" %f", &outputs[i*nbOutputs+j]);
+		if (feof(stdin))
+		{
+			nbSamples = i;
+			break;
+		}
+	}
+	int topo[3] = {nbInputs, nbHidden, nbOutputs};
+	MLPTrain *net;
+
+	fprintf (stderr, "Got %d samples\n", nbSamples);
+	net = mlp_init(topo, 3, inputs, outputs, nbSamples);
+	rms = mlp_train_backprop(net, inputs, outputs, nbSamples, nbEpoch, 1);
+	printf ("#include \"mlp.h\"\n\n");
+	printf ("/* RMS error was %f, seed was %u */\n\n", rms, seed);
+	printf ("static const float weights[%d] = {\n", (topo[0]+1)*topo[1] + (topo[1]+1)*topo[2]);
+	printf ("\n/* hidden layer */\n");
+	for (i=0;i<(topo[0]+1)*topo[1];i++)
+	{
+		printf ("%gf, ", net->weights[0][i]);
+		if (i%5==4)
+			printf("\n");
+	}
+	printf ("\n/* output layer */\n");
+	for (i=0;i<(topo[1]+1)*topo[2];i++)
+	{
+		printf ("%g, ", net->weights[1][i]);
+		if (i%5==4)
+			printf("\n");
+	}
+	printf ("};\n\n");
+	printf ("static const int topo[3] = {%d, %d, %d};\n\n", topo[0], topo[1], topo[2]);
+	printf ("const MLP net = {\n");
+	printf ("\t3,\n");
+	printf ("\ttopo,\n");
+	printf ("\tweights\n};\n");
+	return 0;
+}
diff --git a/src/mlp_train.h b/src/mlp_train.h
new file mode 100644
index 0000000..1857f64
--- /dev/null
+++ b/src/mlp_train.h
@@ -0,0 +1,86 @@
+/* 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_TRAIN_H_
+#define _MLP_TRAIN_H_
+
+#include <math.h>
+#include <stdlib.h>
+
+double tansig_table[501];
+static inline double tansig_double(double x) 
+{
+	return 2./(1.+exp(-2.*x)) - 1.;
+}
+static inline void build_tansig_table()
+{
+	int i;
+	for (i=0;i<501;i++)
+		tansig_table[i] = tansig_double(.04*(i-250));
+}
+
+static inline double tansig_approx(double x)
+{
+	int i;
+	double y, dy;
+	if (x>=10)
+		return 1;
+	if (x<=-10)
+		return -1;
+	i = lrint(25*x);
+	x -= .04*i;
+	y = tansig_table[250+i];
+	dy = 1-y*y;
+	y = y + x*dy*(1 - y*x);
+	return y;
+}
+
+inline float randn(float sd)
+{
+   float U1, U2, S, x;
+   do {
+      U1 = ((float)rand())/RAND_MAX;
+      U2 = ((float)rand())/RAND_MAX;
+      U1 = 2*U1-1;
+      U2 = 2*U2-1;
+      S = U1*U1 + U2*U2;
+   } while (S >= 1 || S == 0.0f);
+   x = sd*sqrt(-2 * log(S) / S) * U1;
+   return x;
+}
+
+
+typedef struct {
+	int layers;
+	int *topo;
+	double **weights;
+	double **best_weights;
+	double *in_rate;
+} MLPTrain;
+
+
+#endif /* _MLP_TRAIN_H_ */
diff --git a/src/opus.c b/src/opus.c
index d6ae7ba..170bc4b 100644
--- a/src/opus.c
+++ b/src/opus.c
@@ -32,6 +32,105 @@
 #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;
+
+   /* 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);
+         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)
diff --git a/src/opus_decoder.c b/src/opus_decoder.c
index ad5f747..5b56ac1 100644
--- a/src/opus_decoder.c
+++ b/src/opus_decoder.c
@@ -46,6 +46,7 @@
 #include "structs.h"
 #include "define.h"
 #include "mathops.h"
+#include "cpu_support.h"
 
 struct OpusDecoder {
    int          celt_dec_offset;
@@ -65,8 +66,12 @@
    int          frame_size;
    int          prev_redundancy;
    int          last_packet_duration;
+#ifndef FIXED_POINT
+   opus_val16   softclip_mem[2];
+#endif
 
    opus_uint32  rangeFinal;
+   int arch;
 };
 
 #ifdef FIXED_POINT
@@ -116,6 +121,7 @@
    st->Fs = Fs;
    st->DecControl.API_sampleRate = st->Fs;
    st->DecControl.nChannelsAPI      = st->channels;
+   st->arch = opus_select_arch();
 
    /* Reset decoder */
    ret = silk_InitDecoder( silk_dec );
@@ -201,8 +207,14 @@
    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);
-   VARDECL(opus_val16, pcm_transition);
+   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;
+   int redundant_audio_size;
    VARDECL(opus_val16, redundant_audio);
 
    int audiosize;
@@ -262,16 +274,26 @@
       multiple calls */
    if (data==NULL  && mode != MODE_SILK_ONLY)
       frame_size = IMIN(frame_size, F20);
-   ALLOC(pcm_transition, F5*st->channels, opus_val16);
 
+   pcm_transition_silk_size = 0;
+   pcm_transition_celt_size = 0;
    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)
-         opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);
+         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)
    {
@@ -282,8 +304,9 @@
       frame_size = audiosize;
    }
 
-   ALLOC(pcm_silk, IMAX(F10, frame_size)*st->channels, opus_int16);
-   ALLOC(redundant_audio, F5*st->channels, opus_val16);
+   /* Don't allocate any memory when in CELT-only mode */
+   pcm_silk_size = (mode != MODE_CELT_ONLY) ? IMAX(F10, frame_size)*st->channels : 0;
+   ALLOC(pcm_silk, pcm_silk_size, opus_int16);
 
    /* SILK processing */
    if (mode != MODE_CELT_ONLY)
@@ -397,10 +420,22 @@
    }
 
    if (redundancy)
+   {
       transition = 0;
+      pcm_transition_silk_size=0;
+   }
+
+   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 : 0;
+   ALLOC(redundant_audio, redundant_audio_size, opus_val16);
 
    /* 5 ms redundant frame for CELT->SILK*/
    if (redundancy && celt_to_silk)
@@ -514,12 +549,19 @@
 
    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;
 
 }
 
-static int parse_size(const unsigned char *data, opus_int32 len, short *size)
+static int parse_size(const unsigned char *data, opus_int32 len, opus_int16 *size)
 {
    if (len<1)
    {
@@ -541,7 +583,7 @@
 
 static int opus_packet_parse_impl(const unsigned char *data, opus_int32 len,
       int self_delimited, unsigned char *out_toc,
-      const unsigned char *frames[48], short size[48], int *payload_offset)
+      const unsigned char *frames[48], opus_int16 size[48], int *payload_offset)
 {
    int i, bytes;
    int count;
@@ -576,7 +618,7 @@
             return OPUS_INVALID_PACKET;
          last_size = len/2;
          /* If last_size doesn't fit in size[0], we'll catch it later */
-         size[0] = (short)last_size;
+         size[0] = (opus_int16)last_size;
       }
       break;
    /* Two VBR frames */
@@ -637,7 +679,7 @@
          if (last_size*count!=len)
             return OPUS_INVALID_PACKET;
          for (i=0;i<count-1;i++)
-            size[i] = (short)last_size;
+            size[i] = (opus_int16)last_size;
       }
       break;
    }
@@ -665,7 +707,7 @@
          1275. Reject them here.*/
       if (last_size > 1275)
          return OPUS_INVALID_PACKET;
-      size[count-1] = (short)last_size;
+      size[count-1] = (opus_int16)last_size;
    }
 
    if (frames)
@@ -681,14 +723,14 @@
       *out_toc = toc;
 
    if (payload_offset)
-      *payload_offset = data-data0;
+      *payload_offset = (int)(data-data0);
 
    return count;
 }
 
 int opus_packet_parse(const unsigned char *data, opus_int32 len,
       unsigned char *out_toc, const unsigned char *frames[48],
-      short size[48], int *payload_offset)
+      opus_int16 size[48], int *payload_offset)
 {
    return opus_packet_parse_impl(data, len, 0, out_toc,
                                  frames, size, payload_offset);
@@ -696,7 +738,7 @@
 
 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, int *packet_offset)
+      int self_delimited, int *packet_offset, int soft_clip)
 {
    int i, nb_samples;
    int count, offset;
@@ -704,7 +746,7 @@
    int tot_offset;
    int packet_frame_size, packet_bandwidth, packet_mode, packet_stream_channels;
    /* 48 x 2.5 ms = 120 ms */
-   short size[48];
+   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 */
@@ -715,12 +757,14 @@
       int pcm_count=0;
       do {
          int ret;
-         ret = opus_decode_frame(st, NULL, 0, pcm, frame_size-pcm_count, 0);
+         ret = opus_decode_frame(st, NULL, 0, pcm+pcm_count*st->channels, frame_size-pcm_count, 0);
          if (ret<0)
             return ret;
-         pcm += st->channels*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)
@@ -740,15 +784,19 @@
       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);
+      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;
-      ret = opus_decode_native(st, NULL, 0, pcm, frame_size-packet_frame_size, 0, 0, NULL);
-      if (ret<0)
+      if (frame_size-packet_frame_size!=0)
       {
-         st->last_packet_duration = duration_copy;
-         return ret;
+         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;
@@ -759,8 +807,12 @@
             packet_frame_size, 1);
       if (ret<0)
          return ret;
-      st->last_packet_duration = frame_size;
-      return frame_size;
+      else {
+         if (OPUS_CHECK_ARRAY(pcm, frame_size*st->channels))
+            OPUS_PRINT_INT(frame_size);
+         st->last_packet_duration = frame_size;
+         return frame_size;
+      }
    }
    tot_offset = 0;
    if (count < 0)
@@ -781,17 +833,25 @@
    for (i=0;i<count;i++)
    {
       int ret;
-      ret = opus_decode_frame(st, data, size[i], pcm, frame_size-nb_samples, decode_fec);
+      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];
       tot_offset += size[i];
-      pcm += ret*st->channels;
       nb_samples += ret;
    }
    if (packet_offset != NULL)
       *packet_offset = tot_offset;
    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;
 }
 
@@ -800,7 +860,7 @@
 int opus_decode(OpusDecoder *st, const unsigned char *data,
       opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
 {
-   return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL);
+   return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL, 0);
 }
 
 #ifndef DISABLE_FLOAT_API
@@ -813,7 +873,7 @@
 
    ALLOC(out, frame_size*st->channels, opus_int16);
 
-   ret = opus_decode_native(st, data, len, out, frame_size, decode_fec, 0, NULL);
+   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++)
@@ -841,7 +901,7 @@
 
    ALLOC(out, frame_size*st->channels, float);
 
-   ret = opus_decode_native(st, data, len, out, frame_size, decode_fec, 0, NULL);
+   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++)
@@ -854,7 +914,7 @@
 int opus_decode_float(OpusDecoder *st, const unsigned char *data,
       opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
 {
-   return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL);
+   return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL, 0);
 }
 
 #endif
@@ -877,12 +937,20 @@
    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;
@@ -901,10 +969,9 @@
    case OPUS_GET_SAMPLE_RATE_REQUEST:
    {
       opus_int32 *value = va_arg(ap, opus_int32*);
-      if (value==NULL)
+      if (!value)
       {
-         ret = OPUS_BAD_ARG;
-         break;
+         goto bad_arg;
       }
       *value = st->Fs;
    }
@@ -912,10 +979,9 @@
    case OPUS_GET_PITCH_REQUEST:
    {
       opus_int32 *value = va_arg(ap, opus_int32*);
-      if (value==NULL)
+      if (!value)
       {
-         ret = OPUS_BAD_ARG;
-         break;
+         goto bad_arg;
       }
       if (st->prev_mode == MODE_CELT_ONLY)
          celt_decoder_ctl(celt_dec, OPUS_GET_PITCH(value));
@@ -926,10 +992,9 @@
    case OPUS_GET_GAIN_REQUEST:
    {
       opus_int32 *value = va_arg(ap, opus_int32*);
-      if (value==NULL)
+      if (!value)
       {
-         ret = OPUS_BAD_ARG;
-         break;
+         goto bad_arg;
       }
       *value = st->decode_gain;
    }
@@ -939,8 +1004,7 @@
        opus_int32 value = va_arg(ap, opus_int32);
        if (value<-32768 || value>32767)
        {
-          ret = OPUS_BAD_ARG;
-          break;
+          goto bad_arg;
        }
        st->decode_gain = value;
    }
@@ -948,6 +1012,10 @@
    case OPUS_GET_LAST_PACKET_DURATION_REQUEST:
    {
       opus_uint32 *value = va_arg(ap, opus_uint32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
       *value = st->last_packet_duration;
    }
    break;
@@ -959,6 +1027,9 @@
 
    va_end(ap);
    return ret;
+bad_arg:
+   va_end(ap);
+   return OPUS_BAD_ARG;
 }
 
 void opus_decoder_destroy(OpusDecoder *st)
diff --git a/src/opus_demo.c b/src/opus_demo.c
index 09b12a3..9771ed8 100644
--- a/src/opus_demo.c
+++ b/src/opus_demo.c
@@ -38,6 +38,7 @@
 #include "debug.h"
 #include "opus_types.h"
 #include "opus_private.h"
+#include "opus_multistream.h"
 
 #define MAX_PACKET 1500
 
@@ -53,6 +54,7 @@
     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, "-variable-duration   : enable frames of variable duration (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> : frame size in ms; default: 20 \n" );
     fprintf(stderr, "-max_payload <bytes> : maximum payload size in bytes, default: 1024\n" );
@@ -192,6 +194,35 @@
       {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;
@@ -221,6 +252,8 @@
     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=-1;
     const char *bandwidth_string;
     int lost = 0, lost_prev = 1;
@@ -239,6 +272,10 @@
     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 )
     {
@@ -246,6 +283,7 @@
        return EXIT_FAILURE;
     }
 
+    tot_in=tot_out=0;
     fprintf(stderr, "%s\n", opus_get_version_string());
 
     args = 1;
@@ -306,7 +344,7 @@
     forcechannels = OPUS_AUTO;
     use_dtx = 0;
     packet_loss_perc = 0;
-    max_frame_size = 960*6;
+    max_frame_size = 2*48000;
     curr_read=0;
 
     while( args < argc - 2 ) {
@@ -374,6 +412,14 @@
             check_encoder_option(decode_only, "-cvbr");
             cvbr = 1;
             args++;
+        } else if( strcmp( argv[ args ], "-variable-duration" ) == 0 ) {
+            check_encoder_option(decode_only, "-variable-duration");
+            variable_duration = OPUS_FRAMESIZE_VARIABLE;
+            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;
@@ -499,6 +545,7 @@
 
        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)
     {
@@ -554,6 +601,26 @@
     if ( use_inbandfec ) {
         data[1] = (unsigned char*)calloc(max_payload_bytes,sizeof(char));
     }
+    if(delayed_decision)
+    {
+       if (variable_duration!=OPUS_FRAMESIZE_VARIABLE)
+       {
+          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
+             variable_duration = OPUS_FRAMESIZE_60_MS;
+          opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
+       }
+       frame_size = 2*48000;
+    }
     while (!stop)
     {
         if (delayed_celt)
@@ -617,22 +684,28 @@
                 opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(mode_list[curr_mode][3]));
                 frame_size = mode_list[curr_mode][2];
             }
-            err = fread(fbytes, sizeof(short)*channels, frame_size, fin);
+            err = fread(fbytes, sizeof(short)*channels, frame_size-remaining, fin);
             curr_read = err;
+            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]=s;
+                in[i+remaining*channels]=s;
             }
-            if (curr_read < frame_size)
+            if (curr_read+remaining < frame_size)
             {
-                for (i=curr_read*channels;i<frame_size*channels;i++)
+                for (i=(curr_read+remaining)*channels;i<frame_size*channels;i++)
                    in[i] = 0;
-                stop = 1;
+                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;
@@ -681,6 +754,7 @@
                fprintf(stderr, "Error writing.\n");
                return EXIT_FAILURE;
             }
+            tot_samples += nb_encoded;
         } else {
             int output_samples;
             lost = len[toggle]==0 || (packet_loss_perc>0 && rand()%100 < packet_loss_perc);
@@ -693,9 +767,11 @@
                 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 {
@@ -703,6 +779,11 @@
                 }
                 if (output_samples>0)
                 {
+                    if (!decode_only && tot_out + output_samples > tot_in)
+                    {
+                       stop=1;
+                       output_samples  = tot_in-tot_out;
+                    }
                     if (output_samples>skip) {
                        int i;
                        for(i=0;i<(output_samples-skip)*channels;i++)
@@ -716,6 +797,7 @@
                           fprintf(stderr, "Error writing.\n");
                           return EXIT_FAILURE;
                        }
+                       tot_out += output_samples-skip;
                     }
                     if (output_samples<skip) skip -= output_samples;
                     else skip = 0;
@@ -723,6 +805,7 @@
                    fprintf(stderr, "error decoding frame: %s\n",
                                    opus_strerror(output_samples));
                 }
+                tot_samples += output_samples;
             }
         }
 
@@ -767,7 +850,7 @@
         toggle = (toggle + use_inbandfec) & 1;
     }
     fprintf (stderr, "average bitrate:             %7.3f kb/s\n",
-                     1e-3*bits*sampling_rate/(frame_size*(double)count));
+                     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)
diff --git a/src/opus_encoder.c b/src/opus_encoder.c
index aae3125..f6f0ce5 100644
--- a/src/opus_encoder.c
+++ b/src/opus_encoder.c
@@ -40,7 +40,9 @@
 #include "arch.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"
@@ -50,6 +52,12 @@
 
 #define MAX_ENCODER_BUFFER 480
 
+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;
@@ -66,14 +74,18 @@
     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;
 
 #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;
@@ -83,9 +95,16 @@
     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
+    TonalityAnalysisState analysis;
+    int          detected_bandwidth;
+    int          analysis_offset;
+#endif
     opus_uint32  rangeFinal;
+    int arch;
 };
 
 /* Transition tables for the voice and music. First column is the
@@ -94,8 +113,8 @@
 static const opus_int32 mono_voice_bandwidth_thresholds[8] = {
         11000, 1000, /* NB<->MB */
         14000, 1000, /* MB<->WB */
-        21000, 2000, /* WB<->SWB */
-        29000, 2000, /* SWB<->FB */
+        17000, 1000, /* WB<->SWB */
+        20000, 1000, /* SWB<->FB */
 };
 static const opus_int32 mono_music_bandwidth_thresholds[8] = {
         14000, 1000, /* MB not allowed */
@@ -116,14 +135,14 @@
         48000, 2000, /* SWB<->FB */
 };
 /* Threshold bit-rates for switching between mono and stereo */
-static const opus_int32 stereo_voice_threshold = 26000;
-static const opus_int32 stereo_music_threshold = 36000;
+static const opus_int32 stereo_voice_threshold = 31000;
+static const opus_int32 stereo_music_threshold = 31000;
 
 /* Threshold bit-rate for switching between SILK/hybrid and CELT-only */
 static const opus_int32 mode_thresholds[2][2] = {
       /* voice */ /* music */
-      {  48000,      24000}, /* mono */
-      {  48000,      24000}, /* stereo */
+      {  64000,      20000}, /* mono */
+      {  36000,      20000}, /* stereo */
 };
 
 int opus_encoder_get_size(int channels)
@@ -167,6 +186,8 @@
 
     st->Fs = Fs;
 
+    st->arch = opus_select_arch();
+
     ret = silk_InitEncoder( silk_enc, &st->silk_mode );
     if(ret)return OPUS_INTERNAL_ERROR;
 
@@ -180,7 +201,7 @@
     st->silk_mode.payloadSize_ms            = 20;
     st->silk_mode.bitRate                   = 25000;
     st->silk_mode.packetLossPercentage      = 0;
-    st->silk_mode.complexity                = 10;
+    st->silk_mode.complexity                = 9;
     st->silk_mode.useInBandFEC              = 0;
     st->silk_mode.useDTX                    = 0;
     st->silk_mode.useCBR                    = 0;
@@ -191,7 +212,7 @@
     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(10));
+    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) */
@@ -206,12 +227,15 @@
     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;
@@ -322,7 +346,7 @@
 
         S[ 0 ] = S[1] - vout*A[0] + B[1]*inval;
 
-        S[ 1 ] = - vout*A[1] + B[2]*inval;
+        S[ 1 ] = - vout*A[1] + B[2]*inval + VERY_SMALL;
 
         /* Scale back to Q0 and saturate */
         out[ k*stride ] = vout;
@@ -365,6 +389,56 @@
 #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]), 15);
+         /* 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, 15), 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 c, i;
+   float coef;
+
+   coef = 4.0f*cutoff_Hz/Fs;
+   for (c=0;c<channels;c++)
+   {
+      for (i=0;i<len;i++)
+      {
+         opus_val32 x, tmp, y;
+         x = in[channels*i+c];
+         /* First stage */
+         tmp = x-hp_mem[2*c];
+         hp_mem[2*c] = hp_mem[2*c] + coef*(x - hp_mem[2*c]) + VERY_SMALL;
+         /* Second stage */
+         y = tmp - hp_mem[2*c+1];
+         hp_mem[2*c+1] = hp_mem[2*c+1] + coef*(tmp - hp_mem[2*c+1]) + VERY_SMALL;
+         out[channels*i+c] = y;
+      }
+   }
+}
+#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)
 {
@@ -397,6 +471,45 @@
     }
 }
 
+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;
@@ -438,15 +551,412 @@
     return st->user_bitrate_bps;
 }
 
-#ifdef FIXED_POINT
-#define opus_encode_native opus_encode
-opus_int32 opus_encode(OpusEncoder *st, const opus_val16 *pcm, int frame_size,
-                unsigned char *data, opus_int32 out_data_bytes)
-#else
-#define opus_encode_native opus_encode_float
-opus_int32 opus_encode_float(OpusEncoder *st, const opus_val16 *pcm, int frame_size,
-                      unsigned char *data, opus_int32 out_data_bytes)
+#ifndef DISABLE_FLOAT_API
+/* Don't use more than 60 ms for the frame size analysis */
+#define MAX_DYNAMIC_FRAMESIZE 24
+/* Estimates how much the bitrate will be boosted based on the sub-frame energy */
+static float transient_boost(const float *E, const float *E_1, int LM, int maxM)
+{
+   int i;
+   int M;
+   float sumE=0, sumE_1=0;
+   float metric;
+
+   M = IMIN(maxM, (1<<LM)+1);
+   for (i=0;i<M;i++)
+   {
+      sumE += E[i];
+      sumE_1 += E_1[i];
+   }
+   metric = sumE*sumE_1/(M*M);
+   /*if (LM==3)
+      printf("%f\n", metric);*/
+   /*return metric>10 ? 1 : 0;*/
+   /*return MAX16(0,1-exp(-.25*(metric-2.)));*/
+   return MIN16(1,(float)sqrt(MAX16(0,.05f*(metric-2))));
+}
+
+/* Viterbi decoding trying to find the best frame size combination using look-ahead
+
+   State numbering:
+    0: unused
+    1:  2.5 ms
+    2:  5 ms (#1)
+    3:  5 ms (#2)
+    4: 10 ms (#1)
+    5: 10 ms (#2)
+    6: 10 ms (#3)
+    7: 10 ms (#4)
+    8: 20 ms (#1)
+    9: 20 ms (#2)
+   10: 20 ms (#3)
+   11: 20 ms (#4)
+   12: 20 ms (#5)
+   13: 20 ms (#6)
+   14: 20 ms (#7)
+   15: 20 ms (#8)
+*/
+static int transient_viterbi(const float *E, const float *E_1, int N, int frame_cost, int rate)
+{
+   int i;
+   float cost[MAX_DYNAMIC_FRAMESIZE][16];
+   int states[MAX_DYNAMIC_FRAMESIZE][16];
+   float best_cost;
+   int best_state;
+   float factor;
+   /* Take into account that we damp VBR in the 32 kb/s to 64 kb/s range. */
+   if (rate<80)
+      factor=0;
+   else if (rate>160)
+      factor=1;
+   else
+      factor = (rate-80.f)/80.f;
+   /* Makes variable framesize less aggressive at lower bitrates, but I can't
+      find any valid theoretical justification for this (other than it seems
+      to help) */
+   for (i=0;i<16;i++)
+   {
+      /* Impossible state */
+      states[0][i] = -1;
+      cost[0][i] = 1e10;
+   }
+   for (i=0;i<4;i++)
+   {
+      cost[0][1<<i] = (frame_cost + rate*(1<<i))*(1+factor*transient_boost(E, E_1, i, N+1));
+      states[0][1<<i] = i;
+   }
+   for (i=1;i<N;i++)
+   {
+      int j;
+
+      /* Follow continuations */
+      for (j=2;j<16;j++)
+      {
+         cost[i][j] = cost[i-1][j-1];
+         states[i][j] = j-1;
+      }
+
+      /* New frames */
+      for(j=0;j<4;j++)
+      {
+         int k;
+         float min_cost;
+         float curr_cost;
+         states[i][1<<j] = 1;
+         min_cost = cost[i-1][1];
+         for(k=1;k<4;k++)
+         {
+            float tmp = cost[i-1][(1<<(k+1))-1];
+            if (tmp < min_cost)
+            {
+               states[i][1<<j] = (1<<(k+1))-1;
+               min_cost = tmp;
+            }
+         }
+         curr_cost = (frame_cost + rate*(1<<j))*(1+factor*transient_boost(E+i, E_1+i, j, N-i+1));
+         cost[i][1<<j] = min_cost;
+         /* If part of the frame is outside the analysis window, only count part of the cost */
+         if (N-i < (1<<j))
+            cost[i][1<<j] += curr_cost*(float)(N-i)/(1<<j);
+         else
+            cost[i][1<<j] += curr_cost;
+      }
+   }
+
+   best_state=1;
+   best_cost = cost[N-1][1];
+   /* Find best end state (doesn't force a frame to end at N-1) */
+   for (i=2;i<16;i++)
+   {
+      if (cost[N-1][i]<best_cost)
+      {
+         best_cost = cost[N-1][i];
+         best_state = i;
+      }
+   }
+
+   /* Follow transitions back */
+   for (i=N-1;i>=0;i--)
+   {
+      /*printf("%d ", best_state);*/
+      best_state = states[i][best_state];
+   }
+   /*printf("%d\n", best_state);*/
+   return best_state;
+}
+
+int optimize_framesize(const opus_val16 *x, int len, int C, opus_int32 Fs,
+                int bitrate, opus_val16 tonality, opus_val32 *mem, int buffering,
+                downmix_func downmix)
+{
+   int N;
+   int i;
+   float e[MAX_DYNAMIC_FRAMESIZE+4];
+   float e_1[MAX_DYNAMIC_FRAMESIZE+3];
+   float memx;
+   int bestLM=0;
+   int subframe;
+   int pos;
+   VARDECL(opus_val32, sub);
+
+   subframe = Fs/400;
+   ALLOC(sub, subframe, opus_val32);
+   e[0]=mem[0];
+   e_1[0]=1.f/(EPSILON+mem[0]);
+   if (buffering)
+   {
+      /* Consider the CELT delay when not in restricted-lowdelay */
+      /* We assume the buffering is between 2.5 and 5 ms */
+      int offset = 2*subframe - buffering;
+      celt_assert(offset>=0 && offset <= subframe);
+      x += C*offset;
+      len -= offset;
+      e[1]=mem[1];
+      e_1[1]=1.f/(EPSILON+mem[1]);
+      e[2]=mem[2];
+      e_1[2]=1.f/(EPSILON+mem[2]);
+      pos = 3;
+   } else {
+      pos=1;
+   }
+   N=IMIN(len/subframe, MAX_DYNAMIC_FRAMESIZE);
+   memx = x[0];
+   for (i=0;i<N;i++)
+   {
+      float tmp;
+      float tmpx;
+      int j;
+      tmp=EPSILON;
+
+      downmix(x, sub, subframe, i*subframe, 0, -2, C);
+      if (i==0)
+         memx = sub[0];
+      for (j=0;j<subframe;j++)
+      {
+         tmpx = sub[j];
+         tmp += (tmpx-memx)*(tmpx-memx);
+         memx = tmpx;
+      }
+      e[i+pos] = tmp;
+      e_1[i+pos] = 1.f/tmp;
+   }
+   /* Hack to get 20 ms working with APPLICATION_AUDIO
+      The real problem is that the corresponding memory needs to use 1.5 ms
+      from this frame and 1 ms from the next frame */
+   e[i+pos] = e[i+pos-1];
+   if (buffering)
+      N=IMIN(MAX_DYNAMIC_FRAMESIZE, N+2);
+   bestLM = transient_viterbi(e, e_1, N, (int)((1.f+.5f*tonality)*(60*C+40)), bitrate/400);
+   mem[0] = e[1<<bestLM];
+   if (buffering)
+   {
+      mem[1] = e[(1<<bestLM)+1];
+      mem[2] = e[(1<<bestLM)+2];
+   }
+   return bestLM;
+}
+
 #endif
+
+#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 *sub, int subframe, int offset, int c1, int c2, int C)
+{
+   const float *x;
+   opus_val32 scale;
+   int j;
+   x = (const float *)_x;
+   for (j=0;j<subframe;j++)
+      sub[j] = PCM2VAL(x[(j+offset)*C+c1]);
+   if (c2>-1)
+   {
+      for (j=0;j<subframe;j++)
+         sub[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++)
+            sub[j] += PCM2VAL(x[(j+offset)*C+c]);
+      }
+   }
+#ifdef FIXED_POINT
+   scale = (1<<SIG_SHIFT);
+#else
+   scale = 1.f;
+#endif
+   if (C==-2)
+      scale /= C;
+   else
+      scale /= 2;
+   for (j=0;j<subframe;j++)
+      sub[j] *= scale;
+}
+#endif
+
+void downmix_int(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C)
+{
+   const opus_int16 *x;
+   opus_val32 scale;
+   int j;
+   x = (const opus_int16 *)_x;
+   for (j=0;j<subframe;j++)
+      sub[j] = x[(j+offset)*C+c1];
+   if (c2>-1)
+   {
+      for (j=0;j<subframe;j++)
+         sub[j] += x[(j+offset)*C+c2];
+   } else if (c2==-2)
+   {
+      int c;
+      for (c=1;c<C;c++)
+      {
+         for (j=0;j<subframe;j++)
+            sub[j] += x[(j+offset)*C+c];
+      }
+   }
+#ifdef FIXED_POINT
+   scale = (1<<SIG_SHIFT);
+#else
+   scale = 1.f/32768;
+#endif
+   if (C==-2)
+      scale /= C;
+   else
+      scale /= 2;
+   for (j=0;j<subframe;j++)
+      sub[j] *= scale;
+}
+
+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_VARIABLE)
+      new_size = Fs/50;
+   else if (variable_duration >= OPUS_FRAMESIZE_2_5_MS && variable_duration <= OPUS_FRAMESIZE_60_MS)
+      new_size = IMIN(3*Fs/50, (Fs/400)<<(variable_duration-OPUS_FRAMESIZE_2_5_MS));
+   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)
+      return -1;
+   return new_size;
+}
+
+opus_int32 compute_frame_size(const void *analysis_pcm, int frame_size,
+      int variable_duration, int C, opus_int32 Fs, int bitrate_bps,
+      int delay_compensation, downmix_func downmix, opus_val32 *subframe_mem)
+{
+#ifndef DISABLE_FLOAT_API
+   if (variable_duration == OPUS_FRAMESIZE_VARIABLE && frame_size >= Fs/200)
+   {
+      int LM = 3;
+      LM = optimize_framesize(analysis_pcm, frame_size, C, Fs, bitrate_bps,
+            0, subframe_mem, delay_compensation, downmix);
+      while ((Fs/400<<LM)>frame_size)
+         LM--;
+      frame_size = (Fs/400<<LM);
+   } else
+#endif
+   {
+      frame_size = frame_size_select(frame_size, variable_duration, Fs);
+   }
+   if (frame_size<0)
+      return -1;
+   return frame_size;
+}
+
+opus_val16 compute_stereo_width(const opus_val16 *pcm, int frame_size, opus_int32 Fs, StereoWidthState *mem)
+{
+   opus_val16 corr;
+   opus_val16 ldiff;
+   opus_val16 width;
+   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 - 25*Q15ONE/IMAX(50,frame_rate);
+   xx=xy=yy=0;
+   for (i=0;i<frame_size;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))
+   {
+      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 = 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);
+   } else {
+      width = 0;
+      corr=Q15ONE;
+      ldiff=0;
+   }
+   /*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,20*mem->max_follower));
+}
+
+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)
 {
     void *silk_enc;
     CELTEncoder *celt_enc;
@@ -471,7 +981,14 @@
     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;
+    AnalysisInfo analysis_info;
+    int analysis_read_pos_bak=-1;
+    int analysis_read_subframe_bak=-1;
     VARDECL(opus_val16, tmp_prefill);
 
     ALLOC_STACK;
@@ -479,25 +996,70 @@
     max_data_bytes = IMIN(1276, out_data_bytes);
 
     st->rangeFinal = 0;
-    if (400*frame_size != st->Fs && 200*frame_size != st->Fs && 100*frame_size != st->Fs &&
+    if ((!st->variable_duration && 400*frame_size != st->Fs && 200*frame_size != st->Fs && 100*frame_size != st->Fs &&
          50*frame_size != st->Fs &&  25*frame_size != st->Fs &&  50*frame_size != 3*st->Fs)
-    {
-       RESTORE_STACK;
-       return OPUS_BAD_ARG;
-    }
-    if (max_data_bytes<=0)
+         || (400*frame_size < st->Fs)
+         || max_data_bytes<=0
+         )
     {
        RESTORE_STACK;
        return OPUS_BAD_ARG;
     }
     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);
+
+    analysis_info.valid = 0;
+    celt_encoder_ctl(celt_enc, CELT_GET_MODE(&celt_mode));
+#ifndef DISABLE_FLOAT_API
+#ifdef FIXED_POINT
+    if (st->silk_mode.complexity >= 10 && st->Fs==48000)
+#else
+    if (st->silk_mode.complexity >= 7 && st->Fs==48000)
+#endif
+    {
+       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);
+    }
+#endif
+
+    st->voice_ratio = -1;
+
+#ifndef DISABLE_FLOAT_API
+    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;
+    }
+#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;
@@ -540,8 +1102,12 @@
     else if (st->signal_type == OPUS_SIGNAL_MUSIC)
        voice_est = 0;
     else if (st->voice_ratio >= 0)
+    {
        voice_est = st->voice_ratio*327>>8;
-    else if (st->application == OPUS_APPLICATION_VOIP)
+       /* 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;
@@ -561,9 +1127,9 @@
           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 -= 4000;
+             stereo_threshold -= 1000;
           else
-             stereo_threshold += 4000;
+             stereo_threshold += 1000;
           st->stream_channels = (equiv_rate > stereo_threshold) ? 2 : 1;
        } else {
           st->stream_channels = st->channels;
@@ -592,15 +1158,21 @@
              st->mode = MODE_SILK_ONLY;
        }
 #else
-       int chan;
        opus_int32 mode_voice, mode_music;
        opus_int32 threshold;
 
-       chan = (st->channels==2) && st->force_channels!=1;
-       mode_voice = mode_thresholds[chan][0];
-       mode_music = mode_thresholds[chan][1];
+       /* 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;
@@ -658,6 +1230,7 @@
        redundancy = 1;
        celt_to_silk = 1;
        st->silk_bw_switch = 0;
+       prefill=1;
     }
 
     if (redundancy)
@@ -750,6 +1323,31 @@
         st->bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
     if (st->Fs <= 8000 && st->bandwidth > OPUS_BANDWIDTH_NARROWBAND)
         st->bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+#ifndef FIXED_POINT
+    /* 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 (st->bitrate_bps <= 18000*st->stream_channels && st->mode == MODE_CELT_ONLY)
+          min_detected_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+       else if (st->bitrate_bps <= 24000*st->stream_channels && st->mode == MODE_CELT_ONLY)
+          min_detected_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+       else if (st->bitrate_bps <= 30000*st->stream_channels)
+          min_detected_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+       else if (st->bitrate_bps <= 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
+    celt_encoder_ctl(celt_enc, OPUS_SET_LSB_DEPTH(lsb_depth));
 
     /* If max_data_bytes represents less than 8 kb/s, switch to CELT-only mode */
     if (max_data_bytes < (frame_rate > 50 ? 12000 : 8000)*frame_size / (st->Fs * 8))
@@ -758,6 +1356,11 @@
     /* 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;
+       st->mode = MODE_CELT_ONLY;
+    }
 
     /* Can't support higher than wideband for >20 ms frames */
     if (frame_size > st->Fs/50 && (st->mode == MODE_CELT_ONLY || st->bandwidth > OPUS_BANDWIDTH_WIDEBAND))
@@ -765,16 +1368,22 @@
        VARDECL(unsigned char, tmp_data);
        int nb_frames;
        int bak_mode, bak_bandwidth, bak_channels, bak_to_mono;
-       OpusRepacketizer rp;
+       VARDECL(OpusRepacketizer, rp);
        opus_int32 bytes_per_frame;
 
+       if (analysis_read_pos_bak!= -1)
+       {
+          st->analysis.read_pos = analysis_read_pos_bak;
+          st->analysis.read_subframe = analysis_read_subframe_bak;
+       }
 
        nb_frames = frame_size > st->Fs/25 ? 3 : 2;
        bytes_per_frame = IMIN(1276,(out_data_bytes-3)/nb_frames);
 
        ALLOC(tmp_data, nb_frames*bytes_per_frame, unsigned char);
 
-       opus_repacketizer_init(&rp);
+       ALLOC(rp, 1, OpusRepacketizer);
+       opus_repacketizer_init(rp);
 
        bak_mode = st->user_forced_mode;
        bak_bandwidth = st->user_bandwidth;
@@ -796,20 +1405,22 @@
           /* 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*st->Fs/50), st->Fs/50, tmp_data+i*bytes_per_frame, bytes_per_frame);
+          tmp_len = opus_encode_native(st, pcm+i*(st->channels*st->Fs/50), st->Fs/50,
+                tmp_data+i*bytes_per_frame, bytes_per_frame, lsb_depth,
+                NULL, 0, c1, c2, analysis_channels, downmix);
           if (tmp_len<0)
           {
              RESTORE_STACK;
              return OPUS_INTERNAL_ERROR;
           }
-          ret = opus_repacketizer_cat(&rp, tmp_data+i*bytes_per_frame, tmp_len);
+          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(&rp, data, out_data_bytes);
+       ret = opus_repacketizer_out(rp, data, out_data_bytes);
        if (ret<0)
        {
           RESTORE_STACK;
@@ -822,7 +1433,6 @@
        RESTORE_STACK;
        return ret;
     }
-
     curr_bandwidth = st->bandwidth;
 
     /* Chooses the appropriate mode for speech
@@ -839,9 +1449,9 @@
 
     ec_enc_init(&enc, data, max_data_bytes-1);
 
-    ALLOC(pcm_buf, (delay_compensation+frame_size)*st->channels, opus_val16);
-    for (i=0;i<delay_compensation*st->channels;i++)
-       pcm_buf[i] = st->delay_buffer[(st->encoder_buffer-delay_compensation)*st->channels+i];
+    ALLOC(pcm_buf, (total_buffer+frame_size)*st->channels, opus_val16);
+    for (i=0;i<total_buffer*st->channels;i++)
+       pcm_buf[i] = st->delay_buffer[(st->encoder_buffer-total_buffer)*st->channels+i];
 
     if (st->mode == MODE_CELT_ONLY)
        hp_freq_smth1 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
@@ -856,46 +1466,89 @@
 
     if (st->application == OPUS_APPLICATION_VOIP)
     {
-       hp_cutoff(pcm, cutoff_Hz, &pcm_buf[delay_compensation*st->channels], st->hp_mem, frame_size, st->channels, st->Fs);
+       hp_cutoff(pcm, cutoff_Hz, &pcm_buf[total_buffer*st->channels], st->hp_mem, frame_size, st->channels, st->Fs);
     } else {
-       for (i=0;i<frame_size*st->channels;i++)
-          pcm_buf[delay_compensation*st->channels + i] = pcm[i];
+       dc_reject(pcm, 3, &pcm_buf[total_buffer*st->channels], st->hp_mem, frame_size, st->channels, st->Fs);
     }
 
+
+
     /* 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
-        st->silk_mode.bitRate = 8*bytes_target*frame_rate;
+
+        /* Distribute bits between SILK and CELT */
+        total_bitRate = 8 * bytes_target * frame_rate;
         if( st->mode == MODE_HYBRID ) {
-            st->silk_mode.bitRate /= st->stream_channels;
+            int HB_gain_ref;
+            /* Base rate for SILK */
+            st->silk_mode.bitRate = st->stream_channels * ( 5000 + 1000 * ( st->Fs == 100 * frame_size ) );
             if( curr_bandwidth == OPUS_BANDWIDTH_SUPERWIDEBAND ) {
-                if( st->Fs == 100 * frame_size ) {
-                    /* 24 kHz, 10 ms */
-                    st->silk_mode.bitRate = ( ( st->silk_mode.bitRate + 2000 + st->use_vbr * 1000 ) * 2 ) / 3;
-                } else {
-                    /* 24 kHz, 20 ms */
-                    st->silk_mode.bitRate = ( ( st->silk_mode.bitRate + 1000 + st->use_vbr * 1000 ) * 2 ) / 3;
-                }
-            } else {
-                if( st->Fs == 100 * frame_size ) {
-                    /* 48 kHz, 10 ms */
-                    st->silk_mode.bitRate = ( st->silk_mode.bitRate + 8000 + st->use_vbr * 3000 ) / 2;
-                } else {
-                    /* 48 kHz, 20 ms */
-                    st->silk_mode.bitRate = ( st->silk_mode.bitRate + 9000 + st->use_vbr * 1000 ) / 2;
-                }
+                /* SILK gets 2/3 of the remaining bits */
+                st->silk_mode.bitRate += ( total_bitRate - st->silk_mode.bitRate ) * 2 / 3;
+            } else { /* FULLBAND */
+                /* SILK gets 3/5 of the remaining bits */
+                st->silk_mode.bitRate += ( total_bitRate - st->silk_mode.bitRate ) * 3 / 5;
             }
-            st->silk_mode.bitRate *= st->stream_channels;
-            /* don't let SILK use more than 80% */
-            if( st->silk_mode.bitRate > ( st->bitrate_bps - 8*st->Fs/frame_size ) * 4/5 ) {
-                st->silk_mode.bitRate = ( st->bitrate_bps - 8*st->Fs/frame_size ) * 4/5;
+            /* Don't let SILK use more than 80% */
+            if( st->silk_mode.bitRate > total_bitRate * 4/5 ) {
+                st->silk_mode.bitRate = total_bitRate * 4/5;
             }
+            /* Increasingly attenuate high band when it gets allocated fewer bits */
+            celt_rate = total_bitRate - st->silk_mode.bitRate;
+            HB_gain_ref = (curr_bandwidth == OPUS_BANDWIDTH_SUPERWIDEBAND) ? 3000 : 3600;
+            HB_gain = SHL32((opus_val32)celt_rate, 9) / SHR32((opus_val32)celt_rate + st->stream_channels * HB_gain_ref, 6);
+            HB_gain = HB_gain < Q15ONE*6/7 ? HB_gain + Q15ONE/7 : Q15ONE;
+        } 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(.25f, 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 = HALF16(mask_sum / end*st->channels);
+           rate_offset = PSHR32(MULT16_16(srate, masking_depth), DB_SHIFT);
+           rate_offset = MAX32(rate_offset, -2*st->silk_mode.bitRate/3);
+           rate_offset += QCONST16(.4f, DB_SHIFT);
+           st->silk_mode.bitRate += rate_offset;
+           bytes_target += rate_offset * frame_size / (8 * st->Fs);
         }
 
         st->silk_mode.payloadSize_ms = 1000 * frame_size / st->Fs;
@@ -955,6 +1608,18 @@
         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);
+            for(i=0;i<prefill_offset;i++)
+               st->delay_buffer[i]=0;
 #ifdef FIXED_POINT
             pcm_silk = st->delay_buffer;
 #else
@@ -965,10 +1630,10 @@
         }
 
 #ifdef FIXED_POINT
-        pcm_silk = pcm_buf+delay_compensation*st->channels;
+        pcm_silk = pcm_buf+total_buffer*st->channels;
 #else
         for (i=0;i<frame_size*st->channels;i++)
-            pcm_silk[i] = FLOAT2INT16(pcm_buf[delay_compensation*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 ) {
@@ -1053,9 +1718,18 @@
         } else {
             if (st->use_vbr)
             {
+                opus_int32 bonus=0;
+#ifndef DISABLE_FLOAT_API
+                if (st->variable_duration==OPUS_FRAMESIZE_VARIABLE && frame_size != st->Fs/50)
+                {
+                   bonus = (60*st->stream_channels+40)*(st->Fs/frame_size-50);
+                   if (analysis_info.valid)
+                      bonus = (opus_int32)(bonus*(1.f+.5f*analysis_info.tonality));
+                }
+#endif
                 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));
+                celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(st->bitrate_bps+bonus));
                 nb_compr_bytes = max_data_bytes-1-redundancy_bytes;
             } else {
                 nb_compr_bytes = bytes_target;
@@ -1070,24 +1744,27 @@
     if (st->mode != MODE_SILK_ONLY && st->mode != st->prev_mode && st->prev_mode > 0)
     {
        for (i=0;i<st->channels*st->Fs/400;i++)
-          tmp_prefill[i] = st->delay_buffer[(st->encoder_buffer-st->delay_compensation-st->Fs/400)*st->channels + i];
+          tmp_prefill[i] = st->delay_buffer[(st->encoder_buffer-total_buffer-st->Fs/400)*st->channels + i];
     }
 
-    for (i=0;i<st->channels*(st->encoder_buffer-(frame_size+delay_compensation));i++)
+    for (i=0;i<st->channels*(st->encoder_buffer-(frame_size+total_buffer));i++)
         st->delay_buffer[i] = st->delay_buffer[i+st->channels*frame_size];
     for (;i<st->encoder_buffer*st->channels;i++)
-        st->delay_buffer[i] = pcm_buf[(frame_size+delay_compensation-st->encoder_buffer)*st->channels+i];
+        st->delay_buffer[i] = pcm_buf[(frame_size+total_buffer-st->encoder_buffer)*st->channels+i];
 
-
+    /* 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 = 1<<14;
-    if( st->channels == 2 ) {
+       st->silk_mode.stereoWidth_Q14 = IMIN((1<<14),IMAX(0,st->bitrate_bps-32000));
+    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;
-            const CELTMode *celt_mode;
-
-            celt_encoder_ctl(celt_enc, CELT_GET_MODE(&celt_mode));
             g1 = st->hybrid_stereo_width_Q14;
             g2 = (opus_val16)(st->silk_mode.stereoWidth_Q14);
 #ifdef FIXED_POINT
@@ -1144,6 +1821,10 @@
        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
 
     /* 5 ms redundant frame for CELT->SILK */
     if (redundancy && celt_to_silk)
@@ -1268,45 +1949,89 @@
 #ifdef FIXED_POINT
 
 #ifndef DISABLE_FLOAT_API
-opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int frame_size,
+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;
+   int delay_compensation;
    VARDECL(opus_int16, in);
    ALLOC_STACK;
 
-   if(frame_size<0)
-   {
-      RESTORE_STACK;
-      return OPUS_BAD_ARG;
-   }
+   if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+      delay_compensation = 0;
+   else
+      delay_compensation = st->delay_compensation;
+   frame_size = compute_frame_size(pcm, analysis_frame_size,
+         st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
+         delay_compensation, downmix_float, st->analysis.subframe_mem);
 
    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(st, in, frame_size, data, max_data_bytes);
+   ret = opus_encode_native(st, in, frame_size, data, max_data_bytes, 16, pcm, analysis_frame_size, 0, -2, st->channels, downmix_float);
    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;
+   int delay_compensation;
+   if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+      delay_compensation = 0;
+   else
+      delay_compensation = st->delay_compensation;
+   frame_size = compute_frame_size(pcm, analysis_frame_size,
+         st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
+         delay_compensation, downmix_float, st->analysis.subframe_mem);
+   return opus_encode_native(st, pcm, frame_size, data, out_data_bytes, 16, pcm, analysis_frame_size, 0, -2, st->channels, downmix_int);
+}
+
 #else
-opus_int32 opus_encode(OpusEncoder *st, const opus_int16 *pcm, int frame_size,
+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;
+   int delay_compensation;
    VARDECL(float, in);
    ALLOC_STACK;
 
+   if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+      delay_compensation = 0;
+   else
+      delay_compensation = st->delay_compensation;
+   frame_size = compute_frame_size(pcm, analysis_frame_size,
+         st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
+         delay_compensation, downmix_float, st->analysis.subframe_mem);
+
    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_float(st, in, frame_size, data, max_data_bytes);
+   ret = opus_encode_native(st, in, frame_size, data, max_data_bytes, 16, pcm, analysis_frame_size, 0, -2, st->channels, downmix_int);
    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;
+   int delay_compensation;
+   if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+      delay_compensation = 0;
+   else
+      delay_compensation = st->delay_compensation;
+   frame_size = compute_frame_size(pcm, analysis_frame_size,
+         st->variable_duration, st->channels, st->Fs, st->bitrate_bps,
+         delay_compensation, downmix_float, st->analysis.subframe_mem);
+   return opus_encode_native(st, pcm, frame_size, data, out_data_bytes, 24,
+                             pcm, analysis_frame_size, 0, -2, st->channels, downmix_float);
+}
 #endif
 
 
@@ -1339,6 +2064,10 @@
         case OPUS_GET_APPLICATION_REQUEST:
         {
             opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
             *value = st->application;
         }
         break;
@@ -1360,6 +2089,10 @@
         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;
@@ -1367,21 +2100,29 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if((value<1 || value>st->channels) && value != OPUS_AUTO)
-                return OPUS_BAD_ARG;
+            {
+               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)
-                return OPUS_BAD_ARG;
+            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;
@@ -1395,6 +2136,10 @@
         case OPUS_GET_MAX_BANDWIDTH_REQUEST:
         {
             opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
             *value = st->max_bandwidth;
         }
         break;
@@ -1402,7 +2147,9 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if ((value < OPUS_BANDWIDTH_NARROWBAND || value > OPUS_BANDWIDTH_FULLBAND) && value != OPUS_AUTO)
-                return OPUS_BAD_ARG;
+            {
+               goto bad_arg;
+            }
             st->user_bandwidth = value;
             if (st->user_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
                 st->silk_mode.maxInternalSampleRate = 8000;
@@ -1416,6 +2163,10 @@
         case OPUS_GET_BANDWIDTH_REQUEST:
         {
             opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
             *value = st->bandwidth;
         }
         break;
@@ -1423,13 +2174,19 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if(value<0 || value>1)
-                return OPUS_BAD_ARG;
+            {
+               goto bad_arg;
+            }
             st->silk_mode.useDTX = value;
         }
         break;
         case OPUS_GET_DTX_REQUEST:
         {
             opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
             *value = st->silk_mode.useDTX;
         }
         break;
@@ -1437,7 +2194,9 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if(value<0 || value>10)
-                return OPUS_BAD_ARG;
+            {
+               goto bad_arg;
+            }
             st->silk_mode.complexity = value;
             celt_encoder_ctl(celt_enc, OPUS_SET_COMPLEXITY(value));
         }
@@ -1445,6 +2204,10 @@
         case OPUS_GET_COMPLEXITY_REQUEST:
         {
             opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
             *value = st->silk_mode.complexity;
         }
         break;
@@ -1452,13 +2215,19 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if(value<0 || value>1)
-                return OPUS_BAD_ARG;
+            {
+               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;
@@ -1466,7 +2235,9 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if (value < 0 || value > 100)
-                return OPUS_BAD_ARG;
+            {
+               goto bad_arg;
+            }
             st->silk_mode.packetLossPercentage = value;
             celt_encoder_ctl(celt_enc, OPUS_SET_PACKET_LOSS_PERC(value));
         }
@@ -1474,6 +2245,10 @@
         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;
@@ -1481,7 +2256,9 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if(value<0 || value>1)
-                return OPUS_BAD_ARG;
+            {
+               goto bad_arg;
+            }
             st->use_vbr = value;
             st->silk_mode.useCBR = 1-value;
         }
@@ -1489,20 +2266,30 @@
         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>100 || value<-1)
-                goto bad_arg;
+            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;
@@ -1510,13 +2297,19 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if(value<0 || value>1)
-                return OPUS_BAD_ARG;
+            {
+               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;
@@ -1524,19 +2317,29 @@
         {
             opus_int32 value = va_arg(ap, opus_int32);
             if(value!=OPUS_AUTO && value!=OPUS_SIGNAL_VOICE && value!=OPUS_SIGNAL_MUSIC)
-                return OPUS_BAD_ARG;
+            {
+               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;
@@ -1545,10 +2348,9 @@
         case OPUS_GET_SAMPLE_RATE_REQUEST:
         {
             opus_int32 *value = va_arg(ap, opus_int32*);
-            if (value==NULL)
+            if (!value)
             {
-                ret = OPUS_BAD_ARG;
-                break;
+               goto bad_arg;
             }
             *value = st->Fs;
         }
@@ -1556,19 +2358,55 @@
         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);
-            ret = celt_encoder_ctl(celt_enc, OPUS_SET_LSB_DEPTH(value));
+            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*);
-            celt_encoder_ctl(celt_enc, OPUS_GET_LSB_DEPTH(value));
+            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_VARIABLE)
+            {
+               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_RESET_STATE:
@@ -1585,6 +2423,7 @@
            silk_InitEncoder( silk_enc, &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;
@@ -1595,10 +2434,37 @@
         {
             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;
diff --git a/src/opus_multistream.c b/src/opus_multistream.c
index a7f25a5..09c3639 100644
--- a/src/opus_multistream.c
+++ b/src/opus_multistream.c
@@ -37,31 +37,8 @@
 #include "float_cast.h"
 #include "os_support.h"
 
-typedef struct ChannelLayout {
-   int nb_channels;
-   int nb_streams;
-   int nb_coupled_streams;
-   unsigned char mapping[256];
-} ChannelLayout;
 
-struct OpusMSEncoder {
-   ChannelLayout layout;
-   int bitrate;
-   /* Encoder states go here */
-};
-
-struct OpusMSDecoder {
-   ChannelLayout layout;
-   /* Decoder states go here */
-};
-
-#ifdef FIXED_POINT
-#define opus_encode_native opus_encode
-#else
-#define opus_encode_native opus_encode_float
-#endif
-
-static int validate_layout(const ChannelLayout *layout)
+int validate_layout(const ChannelLayout *layout)
 {
    int i, max_channel;
 
@@ -77,7 +54,7 @@
 }
 
 
-static int get_left_channel(const ChannelLayout *layout, int stream_id, int prev)
+int get_left_channel(const ChannelLayout *layout, int stream_id, int prev)
 {
    int i;
    i = (prev<0) ? 0 : prev+1;
@@ -89,7 +66,7 @@
    return -1;
 }
 
-static int get_right_channel(const ChannelLayout *layout, int stream_id, int prev)
+int get_right_channel(const ChannelLayout *layout, int stream_id, int prev)
 {
    int i;
    i = (prev<0) ? 0 : prev+1;
@@ -101,7 +78,7 @@
    return -1;
 }
 
-static int get_mono_channel(const ChannelLayout *layout, int stream_id, int prev)
+int get_mono_channel(const ChannelLayout *layout, int stream_id, int prev)
 {
    int i;
    i = (prev<0) ? 0 : prev+1;
@@ -113,915 +90,3 @@
    return -1;
 }
 
-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;
-}
-
-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);
-}
-
-
-
-int opus_multistream_encoder_init(
-      OpusMSEncoder *st,
-      opus_int32 Fs,
-      int channels,
-      int streams,
-      int coupled_streams,
-      const unsigned char *mapping,
-      int application
-)
-{
-   int coupled_size;
-   int mono_size;
-   int i, ret;
-   char *ptr;
-
-   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
-       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
-      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) || !validate_encoder_layout(&st->layout))
-      return OPUS_BAD_ARG;
-   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;
-      ptr += align(coupled_size);
-   }
-   for (;i<st->layout.nb_streams;i++)
-   {
-      ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 1, application);
-      if(ret!=OPUS_OK)return ret;
-      ptr += align(mono_size);
-   }
-   return OPUS_OK;
-}
-
-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) ||
-       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
-   {
-      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;
-}
-
-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
-);
-
-/* Max size in case the encoder decides to return three frames */
-#define MS_FRAME_TMP (3*1275+7)
-static int opus_multistream_encode_native
-(
-    OpusMSEncoder *st,
-    opus_copy_channel_in_func copy_channel_in,
-    const void *pcm,
-    int frame_size,
-    unsigned char *data,
-    opus_int32 max_data_bytes
-)
-{
-   opus_int32 Fs;
-   int coupled_size;
-   int mono_size;
-   int s;
-   char *ptr;
-   int tot_size;
-   VARDECL(opus_val16, buf);
-   unsigned char tmp_data[MS_FRAME_TMP];
-   OpusRepacketizer rp;
-   ALLOC_STACK;
-
-   ptr = (char*)st + align(sizeof(OpusMSEncoder));
-   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs));
-   /* Validate frame_size before using it to allocate stack space.
-      This mirrors the checks in opus_encode[_float](). */
-   if (400*frame_size != Fs && 200*frame_size != Fs &&
-       100*frame_size != Fs &&  50*frame_size != Fs &&
-        25*frame_size != Fs &&  50*frame_size != 3*Fs)
-   {
-      RESTORE_STACK;
-      return OPUS_BAD_ARG;
-   }
-   ALLOC(buf, 2*frame_size, opus_val16);
-   coupled_size = opus_encoder_get_size(2);
-   mono_size = opus_encoder_get_size(1);
-
-   if (max_data_bytes < 4*st->layout.nb_streams-1)
-   {
-      RESTORE_STACK;
-      return OPUS_BUFFER_TOO_SMALL;
-   }
-   /* Counting ToC */
-   tot_size = 0;
-   for (s=0;s<st->layout.nb_streams;s++)
-   {
-      OpusEncoder *enc;
-      int len;
-      int curr_max;
-
-      opus_repacketizer_init(&rp);
-      enc = (OpusEncoder*)ptr;
-      if (s < st->layout.nb_coupled_streams)
-      {
-         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);
-      } else {
-         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);
-      }
-      /* number of bytes left (+Toc) */
-      curr_max = max_data_bytes - tot_size;
-      /* Reserve three bytes for the last stream and four for the others */
-      curr_max -= IMAX(0,4*(st->layout.nb_streams-s-1)-1);
-      curr_max = IMIN(curr_max,MS_FRAME_TMP);
-      len = opus_encode_native(enc, buf, frame_size, tmp_data, curr_max);
-      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) */
-      opus_repacketizer_cat(&rp, tmp_data, len);
-      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);
-      data += len;
-      tot_size += len;
-   }
-   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;
-   int 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;
-   int 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);
-}
-
-#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);
-}
-#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);
-}
-
-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);
-}
-#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:
-   {
-      int chan, s;
-      opus_int32 value = va_arg(ap, opus_int32);
-      chan = st->layout.nb_streams + st->layout.nb_coupled_streams;
-      value /= chan;
-      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, request, value * (s < st->layout.nb_coupled_streams ? 2 : 1));
-      }
-   }
-   break;
-   case OPUS_GET_BITRATE_REQUEST:
-   {
-      int s;
-      opus_int32 *value = va_arg(ap, opus_int32*);
-      *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:
-   {
-      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;
-      *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_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:
-   {
-      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**);
-      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;
-   default:
-      ret = OPUS_UNIMPLEMENTED;
-      break;
-   }
-
-   va_end(ap);
-   return ret;
-}
-
-void opus_multistream_encoder_destroy(OpusMSEncoder *st)
-{
-    opus_free(st);
-}
-
-
-/* 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) ||
-       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
-      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) ||
-       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
-   {
-      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_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
-)
-{
-   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)
-      return OPUS_BAD_ARG;
-   if (!do_plc && len < 2*st->layout.nb_streams-1)
-      return OPUS_INVALID_PACKET;
-   for (s=0;s<st->layout.nb_streams;s++)
-   {
-      OpusDecoder *dec;
-      int packet_offset, 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_INVALID_PACKET;
-      }
-      packet_offset = 0;
-      ret = opus_decode_native(dec, data, len, buf, frame_size, decode_fec, s!=st->layout.nb_streams-1, &packet_offset);
-      data += packet_offset;
-      len -= packet_offset;
-      if (ret > frame_size)
-      {
-         RESTORE_STACK;
-         return OPUS_BUFFER_TOO_SMALL;
-      }
-      if (s>0 && ret != frame_size)
-      {
-         RESTORE_STACK;
-         return OPUS_INVALID_PACKET;
-      }
-      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;
-   int 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;
-   int 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);
-}
-
-#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);
-}
-#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);
-}
-
-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);
-}
-#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:
-       {
-          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;
-          *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**);
-          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:
-       {
-          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;
-}
-
-
-void opus_multistream_decoder_destroy(OpusMSDecoder *st)
-{
-    opus_free(st);
-}
diff --git a/src/opus_multistream_decoder.c b/src/opus_multistream_decoder.c
new file mode 100644
index 0000000..f3d2311
--- /dev/null
+++ b/src/opus_multistream_decoder.c
@@ -0,0 +1,499 @@
+/* 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) ||
+       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
+      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) ||
+       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
+   {
+      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_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)
+      return OPUS_BAD_ARG;
+   if (!do_plc && len < 2*st->layout.nb_streams-1)
+      return OPUS_INVALID_PACKET;
+   for (s=0;s<st->layout.nb_streams;s++)
+   {
+      OpusDecoder *dec;
+      int packet_offset, 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_INVALID_PACKET;
+      }
+      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 > frame_size)
+      {
+         RESTORE_STACK;
+         return OPUS_BUFFER_TOO_SMALL;
+      }
+      if (s>0 && ret != frame_size)
+      {
+         RESTORE_STACK;
+         return OPUS_INVALID_PACKET;
+      }
+      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:
+       {
+          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:
+       {
+          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/src/opus_multistream_encoder.c b/src/opus_multistream_encoder.c
new file mode 100644
index 0000000..900c4f4
--- /dev/null
+++ b/src/opus_multistream_encoder.c
@@ -0,0 +1,1139 @@
+/* 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"
+
+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
+);
+
+struct OpusMSEncoder {
+   ChannelLayout layout;
+   int lfe_stream;
+   int application;
+   int variable_duration;
+   int surround;
+   opus_int32 bitrate_bps;
+   opus_val32 subframe_mem[3];
+   /* 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);
+   }
+   return (opus_val32*)(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);
+   }
+   return (opus_val32*)ptr;
+}
+
+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))
+      return max;
+#ifdef FIXED_POINT
+   low = SHR32(diff, DB_SHIFT-1);
+   frac = SHL16(diff - SHL16(low, DB_SHIFT-1), 16-DB_SHIFT);
+#else
+   low = 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 c;
+   int i;
+   int LM;
+   int pos[8] = {0};
+   int upsample;
+   int frame_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;
+
+   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, frame_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++)
+   {
+      OPUS_COPY(in, mem+c*overlap, overlap);
+      (*copy_channel_in)(x, 1, pcm, channels, c, len);
+      preemphasis(x, in+overlap, frame_size, 1, upsample, celt_mode->preemph, preemph_mem+c, 0);
+      clt_mdct_forward(&celt_mode->mdct, in, freq, celt_mode->window, overlap, celt_mode->maxLM-LM, 1);
+      if (upsample != 1)
+      {
+         int bound = len;
+         for (i=0;i<bound;i++)
+            freq[i] *= upsample;
+         for (;i<frame_size;i++)
+            freq[i] = 0;
+      }
+
+      compute_band_energies(celt_mode, freq, bandE, 21, 1, 1<<LM);
+      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;
+   } 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,
+      int surround
+)
+{
+   int coupled_size;
+   int mono_size;
+   int i, ret;
+   char *ptr;
+
+   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
+       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
+      return OPUS_BAD_ARG;
+
+   st->layout.nb_channels = channels;
+   st->layout.nb_streams = streams;
+   st->layout.nb_coupled_streams = coupled_streams;
+   st->subframe_mem[0]=st->subframe_mem[1]=st->subframe_mem[2]=0;
+   if (!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) || !validate_encoder_layout(&st->layout))
+      return OPUS_BAD_ARG;
+   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 (surround)
+   {
+      OPUS_CLEAR(ms_get_preemph_mem(st), channels);
+      OPUS_CLEAR(ms_get_window_mem(st), channels*120);
+   }
+   st->surround = surround;
+   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, 0);
+}
+
+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
+)
+{
+   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;
+   } else
+      return OPUS_UNIMPLEMENTED;
+   return opus_multistream_encoder_init_impl(st, Fs, channels, *streams, *coupled_streams,
+         mapping, application, channels>2&&mapping_family==1);
+}
+
+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) ||
+       (coupled_streams+streams>255) || (streams<1) || (coupled_streams<0))
+   {
+      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;
+   OpusMSEncoder *st;
+   if ((channels>255) || (channels<1))
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   st = (OpusMSEncoder *)opus_alloc(opus_multistream_surround_encoder_get_size(channels, mapping_family));
+   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
+      )
+{
+   int i;
+   opus_int32 channel_rate;
+   opus_int32 Fs;
+   char *ptr;
+   int stream_offset;
+   int lfe_offset;
+   int coupled_ratio; /* Q8 */
+   int lfe_ratio;     /* Q8 */
+
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs));
+
+   if (st->bitrate_bps > st->layout.nb_channels*40000)
+      stream_offset = 20000;
+   else
+      stream_offset = st->bitrate_bps/st->layout.nb_channels/2;
+   /* We start by giving each stream (coupled or uncoupled) the same bitrate.
+      This models the main saving of coupled channels over uncoupled. */
+   /* The LFE stream is an exception to the above and gets fewer bits. */
+   lfe_offset = 3500;
+   /* Coupled streams get twice the mono rate after the first 20 kb/s. */
+   coupled_ratio = 512;
+   /* Should depend on the bitrate, for now we assume LFE gets 1/8 the bits of mono */
+   lfe_ratio = 32;
+
+   /* Compute bitrate allocation between streams */
+   if (st->bitrate_bps==OPUS_AUTO)
+   {
+      channel_rate = Fs+60*Fs/frame_size;
+   } else if (st->bitrate_bps==OPUS_BITRATE_MAX)
+   {
+      channel_rate = 300000;
+   } else {
+      int nb_lfe;
+      int nb_uncoupled;
+      int nb_coupled;
+      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;
+      total = (nb_uncoupled<<8)         /* mono */
+            + coupled_ratio*nb_coupled /* stereo */
+            + nb_lfe*lfe_ratio;
+      channel_rate = 256*(st->bitrate_bps-lfe_offset*nb_lfe-stream_offset*(nb_coupled+nb_uncoupled))/total;
+   }
+#ifndef FIXED_POINT
+   if (st->variable_duration==OPUS_FRAMESIZE_VARIABLE && frame_size != Fs/50)
+   {
+      opus_int32 bonus;
+      bonus = 60*(Fs/frame_size-50);
+      channel_rate += bonus;
+   }
+#endif
+
+   for (i=0;i<st->layout.nb_streams;i++)
+   {
+      if (i<st->layout.nb_coupled_streams)
+         rate[i] = stream_offset+(channel_rate*coupled_ratio>>8);
+      else if (i!=st->lfe_stream)
+         rate[i] = stream_offset+channel_rate;
+      else
+         rate[i] = lfe_offset+(channel_rate*lfe_ratio>>8);
+   }
+}
+
+/* Max size in case the encoder decides to return three frames */
+#define MS_FRAME_TMP (3*1275+7)
+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
+)
+{
+   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 complexity;
+   const CELTMode *celt_mode;
+   opus_int32 bitrates[256];
+   opus_val16 bandLogE[42];
+   opus_val32 *mem = NULL;
+   opus_val32 *preemph_mem=NULL;
+   int frame_size;
+   ALLOC_STACK;
+
+   if (st->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_COMPLEXITY(&complexity));
+   opus_encoder_ctl((OpusEncoder*)ptr, CELT_GET_MODE(&celt_mode));
+
+   {
+      opus_int32 delay_compensation;
+      int channels;
+
+      channels = st->layout.nb_streams + st->layout.nb_coupled_streams;
+      opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_LOOKAHEAD(&delay_compensation));
+      delay_compensation -= Fs/400;
+      frame_size = compute_frame_size(pcm, analysis_frame_size,
+            st->variable_duration, channels, Fs, st->bitrate_bps,
+            delay_compensation, downmix, st->subframe_mem);
+   }
+
+   if (400*frame_size < Fs)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   /* Validate frame_size before using it to allocate stack space.
+      This mirrors the checks in opus_encode[_float](). */
+   if (400*frame_size != Fs && 200*frame_size != Fs &&
+       100*frame_size != Fs &&  50*frame_size != Fs &&
+        25*frame_size != Fs &&  50*frame_size != 3*Fs)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   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->surround)
+   {
+      surround_analysis(celt_mode, pcm, bandSMR, mem, preemph_mem, frame_size, 120, st->layout.nb_channels, Fs, copy_channel_in);
+   }
+
+   if (max_data_bytes < 4*st->layout.nb_streams-1)
+   {
+      RESTORE_STACK;
+      return OPUS_BUFFER_TOO_SMALL;
+   }
+
+   /* Compute bitrate allocation between streams (this could be a lot better) */
+   surround_rate_allocation(st, bitrates, 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->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 > 112000)
+            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_FULLBAND));
+         else if (equiv_rate > 76000)
+            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_SUPERWIDEBAND));
+         else if (equiv_rate > 48000)
+            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));
+         }
+      }
+   }
+
+   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;
+
+      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->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->surround)
+         {
+            for (i=0;i<21;i++)
+               bandLogE[i] = bandSMR[21*chan+i];
+         }
+         c1 = chan;
+         c2 = -1;
+      }
+      if (st->surround)
+         opus_encoder_ctl(enc, OPUS_SET_ENERGY_MASK(bandLogE));
+      /* number of bytes left (+Toc) */
+      curr_max = max_data_bytes - tot_size;
+      /* Reserve three bytes for the last stream and four for the others */
+      curr_max -= IMAX(0,4*(st->layout.nb_streams-s-1)-1);
+      curr_max = IMIN(curr_max,MS_FRAME_TMP);
+      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);
+      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) */
+      opus_repacketizer_cat(&rp, tmp_data, len);
+      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);
+      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);
+}
+
+#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);
+}
+#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);
+}
+
+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);
+}
+#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<0 && value!=OPUS_AUTO && value!=OPUS_BITRATE_MAX)
+      {
+         goto bad_arg;
+      }
+      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:
+   {
+      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:
+   {
+      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;
+   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/src/opus_private.h b/src/opus_private.h
index 52482bc..0e739eb 100644
--- a/src/opus_private.h
+++ b/src/opus_private.h
@@ -31,15 +31,29 @@
 
 #include "arch.h"
 #include "opus.h"
+#include "celt.h"
 
 struct OpusRepacketizer {
    unsigned char toc;
    int nb_frames;
    const unsigned char *frames[48];
-   short len[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
@@ -68,16 +82,34 @@
 #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 optimize_framesize(const opus_val16 *x, int len, int C, opus_int32 Fs,
+                int bitrate, opus_val16 tonality, opus_val32 *mem, int buffering,
+                downmix_func downmix);
 
 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 compute_frame_size(const void *analysis_pcm, int frame_size,
+      int variable_duration, int C, opus_int32 Fs, int bitrate_bps,
+      int delay_compensation, downmix_func downmix, opus_val32 *subframe_mem);
+
+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 opus_decode_native(OpusDecoder *st, const unsigned char *data, opus_int32 len,
-      opus_val16 *pcm, int frame_size, int decode_fec, int self_delimited, int *packet_offset);
+      opus_val16 *pcm, int frame_size, int decode_fec, int self_delimited,
+      int *packet_offset, int soft_clip);
 
 /* Make sure everything's aligned to sizeof(void *) bytes */
 static inline int align(int i)
 {
-    return (i+sizeof(void *)-1)&-((int)sizeof(void *));
+    return (i+(int)sizeof(void *)-1)&-(int)sizeof(void *);
 }
 
 opus_int32 opus_repacketizer_out_range_impl(OpusRepacketizer *rp, int begin, int end, unsigned char *data, opus_int32 maxlen, int self_delimited);
diff --git a/src/repacketizer.c b/src/repacketizer.c
index 26315b6..0c5d840 100644
--- a/src/repacketizer.c
+++ b/src/repacketizer.c
@@ -98,7 +98,7 @@
 {
    int i, count;
    opus_int32 tot_size;
-   short *len;
+   opus_int16 *len;
    const unsigned char **frames;
 
    if (begin<0 || begin>=end || end>rp->nb_frames)
diff --git a/src/tansig_table.h b/src/tansig_table.h
new file mode 100644
index 0000000..c76f844
--- /dev/null
+++ b/src/tansig_table.h
@@ -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/tests/run_vectors.sh b/tests/run_vectors.sh
index 1cc445d..116a743 100755
--- a/tests/run_vectors.sh
+++ b/tests/run_vectors.sh
@@ -57,6 +57,11 @@
     exit 0
 fi
 
+if [ ! -x $OPUS_COMPARE ]; then
+    echo ERROR: Compare program not found: $OPUS_COMPARE
+    exit 1
+fi
+
 if [ -x $OPUS_DEMO ]; then
     echo Decoding with $OPUS_DEMO
 else
diff --git a/tests/test_opus_api.c b/tests/test_opus_api.c
index c2d7e10..2b46781 100644
--- a/tests/test_opus_api.c
+++ b/tests/test_opus_api.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2011 Xiph.Org Foundation
+/* Copyright (c) 2011-2013 Xiph.Org Foundation
    Written by Gregory Maxwell */
 /*
    Redistribution and use in source and binary forms, with or without
@@ -147,6 +147,8 @@
    fprintf(stdout,"    opus_decoder_create() ........................ OK.\n");
    fprintf(stdout,"    opus_decoder_init() .......................... OK.\n");
 
+   err=opus_decoder_ctl(dec, OPUS_GET_FINAL_RANGE((opus_uint32 *)NULL));
+   if(err != OPUS_BAD_ARG)test_failed();
    VG_UNDEF(&dec_final_range,sizeof(dec_final_range));
    err=opus_decoder_ctl(dec, OPUS_GET_FINAL_RANGE(&dec_final_range));
    if(err!=OPUS_OK)test_failed();
@@ -159,12 +161,22 @@
    fprintf(stdout,"    OPUS_UNIMPLEMENTED ........................... OK.\n");
    cfgs++;
 
+   err=opus_decoder_ctl(dec, OPUS_GET_BANDWIDTH((opus_int32 *)NULL));
+   if(err != OPUS_BAD_ARG)test_failed();
    VG_UNDEF(&i,sizeof(i));
    err=opus_decoder_ctl(dec, OPUS_GET_BANDWIDTH(&i));
    if(err != OPUS_OK || i!=0)test_failed();
    fprintf(stdout,"    OPUS_GET_BANDWIDTH ........................... OK.\n");
    cfgs++;
 
+   err=opus_decoder_ctl(dec, OPUS_GET_SAMPLE_RATE((opus_int32 *)NULL));
+   if(err != OPUS_BAD_ARG)test_failed();
+   VG_UNDEF(&i,sizeof(i));
+   err=opus_decoder_ctl(dec, OPUS_GET_SAMPLE_RATE(&i));
+   if(err != OPUS_OK || i!=48000)test_failed();
+   fprintf(stdout,"    OPUS_GET_SAMPLE_RATE ......................... OK.\n");
+   cfgs++;
+
    /*GET_PITCH has different execution paths depending on the previously decoded frame.*/
    err=opus_decoder_ctl(dec, OPUS_GET_PITCH(nullvalue));
    if(err!=OPUS_BAD_ARG)test_failed();
@@ -190,6 +202,14 @@
    cfgs++;
    fprintf(stdout,"    OPUS_GET_PITCH ............................... OK.\n");
 
+   err=opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION((opus_int32 *)NULL));
+   if(err != OPUS_BAD_ARG)test_failed();
+   VG_UNDEF(&i,sizeof(i));
+   err=opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&i));
+   if(err != OPUS_OK || i!=960)test_failed();
+   cfgs++;
+   fprintf(stdout,"    OPUS_GET_LAST_PACKET_DURATION ................ OK.\n");
+
    VG_UNDEF(&i,sizeof(i));
    err=opus_decoder_ctl(dec, OPUS_GET_GAIN(&i));
    VG_CHECK(&i,sizeof(i));
@@ -1012,7 +1032,7 @@
       }
    }
    fprintf(stdout,"    code 3 padding (%2d cases) ............... OK.\n",cfgs);
-   cfgs_total+=cfgs;cfgs=0;
+   cfgs_total+=cfgs;
    fprintf(stdout,"    opus_packet_parse ............................ OK.\n");
    fprintf(stdout,"                      All packet parsing tests passed\n");
    fprintf(stdout,"                          (%d API invocations)\n",cfgs_total);
@@ -1120,8 +1140,8 @@
    cfgs++;
    err=opus_encoder_ctl(enc,OPUS_GET_LOOKAHEAD(&i));
    if(err!=OPUS_OK || i<0 || i>32766)test_failed();
-   opus_encoder_destroy(enc);
    cfgs++;
+   opus_encoder_destroy(enc);
 
    VG_UNDEF(&err,sizeof(err));
    enc = opus_encoder_create(48000, 2, OPUS_APPLICATION_AUDIO, &err);
@@ -1145,17 +1165,34 @@
    err=opus_encoder_ctl(enc,OPUS_GET_LOOKAHEAD(&i));
    if(err!=OPUS_OK || i<0 || i>32766)test_failed();
    cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_GET_LOOKAHEAD((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    fprintf(stdout,"    OPUS_GET_LOOKAHEAD ........................... OK.\n");
 
+   err=opus_encoder_ctl(enc,OPUS_GET_SAMPLE_RATE(&i));
+   if(err!=OPUS_OK || i!=48000)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_GET_SAMPLE_RATE((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
+   fprintf(stdout,"    OPUS_GET_SAMPLE_RATE ......................... OK.\n");
+
    if(opus_encoder_ctl(enc,OPUS_UNIMPLEMENTED)!=OPUS_UNIMPLEMENTED)test_failed();
    fprintf(stdout,"    OPUS_UNIMPLEMENTED ........................... OK.\n");
    cfgs++;
 
+   err=opus_encoder_ctl(enc,OPUS_GET_APPLICATION((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_APPLICATION(i),OPUS_GET_APPLICATION(&i),-1,OPUS_AUTO,
      OPUS_APPLICATION_AUDIO,OPUS_APPLICATION_RESTRICTED_LOWDELAY,
      "    OPUS_SET_APPLICATION ......................... OK.\n",
      "    OPUS_GET_APPLICATION ......................... OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_BITRATE((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    if(opus_encoder_ctl(enc,OPUS_SET_BITRATE(1073741832))!=OPUS_OK)test_failed();
    cfgs++;
    VG_UNDEF(&i,sizeof(i));
@@ -1167,6 +1204,9 @@
      "    OPUS_SET_BITRATE ............................. OK.\n",
      "    OPUS_GET_BITRATE ............................. OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_FORCE_CHANNELS((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_FORCE_CHANNELS(i),OPUS_GET_FORCE_CHANNELS(&i),-1,3,
      1,OPUS_AUTO,
      "    OPUS_SET_FORCE_CHANNELS ...................... OK.\n",
@@ -1202,6 +1242,9 @@
    cfgs++;
    if(opus_encoder_ctl(enc,OPUS_SET_BANDWIDTH(OPUS_AUTO))!=OPUS_OK)test_failed();
    cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_GET_BANDWIDTH((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    fprintf(stdout,"    OPUS_GET_BANDWIDTH ........................... OK.\n");
 
    i=-2;
@@ -1232,55 +1275,113 @@
       i!=OPUS_BANDWIDTH_MEDIUMBAND&&i!=OPUS_BANDWIDTH_WIDEBAND&&
       i!=OPUS_BANDWIDTH_FULLBAND))test_failed();
    cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_GET_MAX_BANDWIDTH((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    fprintf(stdout,"    OPUS_GET_MAX_BANDWIDTH ....................... OK.\n");
 
+   err=opus_encoder_ctl(enc,OPUS_GET_DTX((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_DTX(i),OPUS_GET_DTX(&i),-1,2,
      1,0,
      "    OPUS_SET_DTX ................................. OK.\n",
      "    OPUS_GET_DTX ................................. OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_COMPLEXITY((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_COMPLEXITY(i),OPUS_GET_COMPLEXITY(&i),-1,11,
      0,10,
      "    OPUS_SET_COMPLEXITY .......................... OK.\n",
      "    OPUS_GET_COMPLEXITY .......................... OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_INBAND_FEC((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_INBAND_FEC(i),OPUS_GET_INBAND_FEC(&i),-1,2,
      1,0,
      "    OPUS_SET_INBAND_FEC .......................... OK.\n",
      "    OPUS_GET_INBAND_FEC .......................... OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_PACKET_LOSS_PERC((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_PACKET_LOSS_PERC(i),OPUS_GET_PACKET_LOSS_PERC(&i),-1,101,
      100,0,
      "    OPUS_SET_PACKET_LOSS_PERC .................... OK.\n",
      "    OPUS_GET_PACKET_LOSS_PERC .................... OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_VBR((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_VBR(i),OPUS_GET_VBR(&i),-1,2,
      1,0,
      "    OPUS_SET_VBR ................................. OK.\n",
      "    OPUS_GET_VBR ................................. OK.\n")
 
-   /*CHECK_SETGET(OPUS_SET_VOICE_RATIO(i),OPUS_GET_VOICE_RATIO(&i),-2,101,
+/*   err=opus_encoder_ctl(enc,OPUS_GET_VOICE_RATIO((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
+   CHECK_SETGET(OPUS_SET_VOICE_RATIO(i),OPUS_GET_VOICE_RATIO(&i),-2,101,
      0,50,
      "    OPUS_SET_VOICE_RATIO ......................... OK.\n",
-     "    OPUS_GET_VOICE_RATIO ......................... OK.\n")
-   */
+     "    OPUS_GET_VOICE_RATIO ......................... OK.\n")*/
 
+   err=opus_encoder_ctl(enc,OPUS_GET_VBR_CONSTRAINT((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_VBR_CONSTRAINT(i),OPUS_GET_VBR_CONSTRAINT(&i),-1,2,
      1,0,
      "    OPUS_SET_VBR_CONSTRAINT ...................... OK.\n",
      "    OPUS_GET_VBR_CONSTRAINT ...................... OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_SIGNAL((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_SIGNAL(i),OPUS_GET_SIGNAL(&i),-12345,0x7FFFFFFF,
      OPUS_SIGNAL_MUSIC,OPUS_AUTO,
      "    OPUS_SET_SIGNAL .............................. OK.\n",
      "    OPUS_GET_SIGNAL .............................. OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_LSB_DEPTH((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    CHECK_SETGET(OPUS_SET_LSB_DEPTH(i),OPUS_GET_LSB_DEPTH(&i),7,25,16,24,
      "    OPUS_SET_LSB_DEPTH ........................... OK.\n",
      "    OPUS_GET_LSB_DEPTH ........................... OK.\n")
 
+   err=opus_encoder_ctl(enc,OPUS_GET_EXPERT_FRAME_DURATION((opus_int32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_SET_EXPERT_FRAME_DURATION(OPUS_FRAMESIZE_2_5_MS));
+   if(err!=OPUS_OK)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_SET_EXPERT_FRAME_DURATION(OPUS_FRAMESIZE_5_MS));
+   if(err!=OPUS_OK)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_SET_EXPERT_FRAME_DURATION(OPUS_FRAMESIZE_10_MS));
+   if(err!=OPUS_OK)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_SET_EXPERT_FRAME_DURATION(OPUS_FRAMESIZE_20_MS));
+   if(err!=OPUS_OK)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_SET_EXPERT_FRAME_DURATION(OPUS_FRAMESIZE_40_MS));
+   if(err!=OPUS_OK)test_failed();
+   cfgs++;
+   err=opus_encoder_ctl(enc,OPUS_SET_EXPERT_FRAME_DURATION(OPUS_FRAMESIZE_60_MS));
+   if(err!=OPUS_OK)test_failed();
+   cfgs++;
+   CHECK_SETGET(OPUS_SET_EXPERT_FRAME_DURATION(i),OPUS_GET_EXPERT_FRAME_DURATION(&i),0,-1,
+     OPUS_FRAMESIZE_VARIABLE,OPUS_FRAMESIZE_ARG,
+     "    OPUS_SET_EXPERT_FRAME_DURATION ............... OK.\n",
+     "    OPUS_GET_EXPERT_FRAME_DURATION ............... OK.\n")
+
    /*OPUS_SET_FORCE_MODE is not tested here because it's not a public API, however the encoder tests use it*/
 
+   err=opus_encoder_ctl(enc,OPUS_GET_FINAL_RANGE((opus_uint32 *)NULL));
+   if(err!=OPUS_BAD_ARG)test_failed();
+   cfgs++;
    if(opus_encoder_ctl(enc,OPUS_GET_FINAL_RANGE(&enc_final_range))!=OPUS_OK)test_failed();
    cfgs++;
    fprintf(stdout,"    OPUS_GET_FINAL_RANGE ......................... OK.\n");
diff --git a/tests/test_opus_decode.c b/tests/test_opus_decode.c
index e2c04c2..44a0ae5 100644
--- a/tests/test_opus_decode.c
+++ b/tests/test_opus_decode.c
@@ -111,6 +111,10 @@
          if(opus_decoder_ctl(dec[t], OPUS_GET_LAST_PACKET_DURATION(&dur))!=OPUS_OK)test_failed();
          if(dur!=120/factor)test_failed();
 
+         /*Test on a size which isn't a multiple of 2.5ms*/
+         out_samples = opus_decode(dec[t], 0, 0, outbuf, 120/factor+2, fec);
+         if(out_samples!=OPUS_BAD_ARG)test_failed();
+
          /*Test null pointer input*/
          out_samples = opus_decode(dec[t], 0, -1, outbuf, 120/factor, fec);
          if(out_samples!=120/factor)test_failed();
@@ -230,8 +234,8 @@
      /*We only test a subset of the modes here simply because the longer
        durations end up taking a long time.*/
       static const int cmodes[4]={16,20,24,28};
-      static const opus_uint32 cres[4]={116290185,2172123586,2172123586,2172123586};
-      static const opus_uint32 lres[3]={3285687739,1481572662,694350475};
+      static const opus_uint32 cres[4]={116290185,2172123586u,2172123586u,2172123586u};
+      static const opus_uint32 lres[3]={3285687739u,1481572662,694350475};
       static const int lmodes[3]={0,4,8};
       int mode=fast_rand()%4;
 
diff --git a/tests/test_opus_encode.c b/tests/test_opus_encode.c
index b80def3..29c47d9 100644
--- a/tests/test_opus_encode.c
+++ b/tests/test_opus_encode.c
@@ -1,4 +1,4 @@
-/* Copyright (c) 2011 Xiph.Org Foundation
+/* Copyright (c) 2011-2013 Xiph.Org Foundation
    Written by Gregory Maxwell */
 /*
    Redistribution and use in source and binary forms, with or without
@@ -247,7 +247,11 @@
          do {
             int bw,len,out_samples,frame_size;
             frame_size=frame[j];
-            if(fast_rand()%50==0)opus_encoder_ctl(enc, OPUS_RESET_STATE);
+            if(fast_rand()%100==0)opus_encoder_ctl(enc, OPUS_RESET_STATE);
+            if(fast_rand()%10==0){
+               int complex=fast_rand()%11;
+               if(opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complex))!=OPUS_OK)test_failed();
+            }
             if(fast_rand()%50==0)opus_decoder_ctl(dec, OPUS_RESET_STATE);
             if(opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(rc==0))!=OPUS_OK)test_failed();
             if(opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_SILK_ONLY+modes[j]))!=OPUS_OK)test_failed();
diff --git a/version.mk b/version.mk
index ef30573..519ff14 100644
--- a/version.mk
+++ b/version.mk
@@ -1,2 +1,2 @@
 # static version string; update manually every release.
-OPUS_VERSION = "1.0.2"
+PACKAGE_VERSION = "1.1-beta"
diff --git a/win32/VS2010/celt.vcxproj b/win32/VS2010/celt.vcxproj
new file mode 100644
index 0000000..f107fec
--- /dev/null
+++ b/win32/VS2010/celt.vcxproj
@@ -0,0 +1,255 @@
+<?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>
+  <ItemGroup>
+    <ClCompile Include="..\..\celt\bands.c" />
+    <ClCompile Include="..\..\celt\celt.c" />
+    <ClCompile Include="..\..\celt\celt_decoder.c" />
+    <ClCompile Include="..\..\celt\celt_encoder.c" />
+    <ClCompile Include="..\..\celt\celt_lpc.c" />
+    <ClCompile Include="..\..\celt\cwrs.c" />
+    <ClCompile Include="..\..\celt\entcode.c" />
+    <ClCompile Include="..\..\celt\entdec.c" />
+    <ClCompile Include="..\..\celt\entenc.c" />
+    <ClCompile Include="..\..\celt\kiss_fft.c" />
+    <ClCompile Include="..\..\celt\laplace.c" />
+    <ClCompile Include="..\..\celt\mathops.c" />
+    <ClCompile Include="..\..\celt\mdct.c" />
+    <ClCompile Include="..\..\celt\modes.c" />
+    <ClCompile Include="..\..\celt\pitch.c" />
+    <ClCompile Include="..\..\celt\quant_bands.c" />
+    <ClCompile Include="..\..\celt\rate.c" />
+    <ClCompile Include="..\..\celt\vq.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\celt\arch.h" />
+    <ClInclude Include="..\..\celt\bands.h" />
+    <ClInclude Include="..\..\celt\celt.h" />
+    <ClInclude Include="..\..\celt\celt_lpc.h" />
+    <ClInclude Include="..\..\celt\cwrs.h" />
+    <ClInclude Include="..\..\celt\ecintrin.h" />
+    <ClInclude Include="..\..\celt\entcode.h" />
+    <ClInclude Include="..\..\celt\entdec.h" />
+    <ClInclude Include="..\..\celt\entenc.h" />
+    <ClInclude Include="..\..\celt\fixed_c5x.h" />
+    <ClInclude Include="..\..\celt\fixed_c6x.h" />
+    <ClInclude Include="..\..\celt\fixed_debug.h" />
+    <ClInclude Include="..\..\celt\fixed_generic.h" />
+    <ClInclude Include="..\..\celt\float_cast.h" />
+    <ClInclude Include="..\..\celt\kiss_fft.h" />
+    <ClInclude Include="..\..\celt\laplace.h" />
+    <ClInclude Include="..\..\celt\mathops.h" />
+    <ClInclude Include="..\..\celt\mdct.h" />
+    <ClInclude Include="..\..\celt\mfrngcod.h" />
+    <ClInclude Include="..\..\celt\modes.h" />
+    <ClInclude Include="..\..\celt\os_support.h" />
+    <ClInclude Include="..\..\celt\pitch.h" />
+    <ClInclude Include="..\..\celt\quant_bands.h" />
+    <ClInclude Include="..\..\celt\rate.h" />
+    <ClInclude Include="..\..\celt\stack_alloc.h" />
+    <ClInclude Include="..\..\celt\static_modes_fixed.h" />
+    <ClInclude Include="..\..\celt\static_modes_float.h" />
+    <ClInclude Include="..\..\celt\vq.h" />
+    <ClInclude Include="..\..\celt\_kiss_fft_guts.h" />
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{245603E3-F580-41A5-9632-B25FE3372CBF}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>celt</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>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</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)'=='Release|x64'" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <CustomBuildBeforeTargets>
+    </CustomBuildBeforeTargets>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/celt.vcxproj.filters b/win32/VS2010/celt.vcxproj.filters
new file mode 100644
index 0000000..e3a1d97
--- /dev/null
+++ b/win32/VS2010/celt.vcxproj.filters
@@ -0,0 +1,162 @@
+<?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>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\celt\celt_decoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\celt_encoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\celt_lpc.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\cwrs.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\entcode.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\entdec.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\entenc.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\kiss_fft.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\laplace.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\mathops.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\mdct.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\modes.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\pitch.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\quant_bands.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\rate.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\vq.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\bands.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\celt\celt.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\celt\cwrs.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\ecintrin.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\entcode.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\entdec.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\entenc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\fixed_c5x.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\fixed_c6x.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\fixed_debug.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\fixed_generic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\float_cast.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\kiss_fft.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\laplace.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\mathops.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\mdct.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\mfrngcod.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\modes.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\os_support.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\pitch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\quant_bands.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\rate.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\stack_alloc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\static_modes_fixed.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\static_modes_float.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\vq.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\_kiss_fft_guts.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\arch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\bands.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\celt.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\celt_lpc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/opus.sln b/win32/VS2010/opus.sln
new file mode 100644
index 0000000..2a03f94
--- /dev/null
+++ b/win32/VS2010/opus.sln
@@ -0,0 +1,130 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opus", "opus.vcxproj", "{219EC965-228A-1824-174D-96449D05F88A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "celt", "celt.vcxproj", "{245603E3-F580-41A5-9632-B25FE3372CBF}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opus_demo", "opus_demo.vcxproj", "{016C739D-6389-43BF-8D88-24B2BF6F620F}"
+	ProjectSection(ProjectDependencies) = postProject
+		{219EC965-228A-1824-174D-96449D05F88A} = {219EC965-228A-1824-174D-96449D05F88A}
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782} = {9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}
+		{245603E3-F580-41A5-9632-B25FE3372CBF} = {245603E3-F580-41A5-9632-B25FE3372CBF}
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16} = {C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_opus_api", "test_opus_api.vcxproj", "{1D257A17-D254-42E5-82D6-1C87A6EC775A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{219EC965-228A-1824-174D-96449D05F88A} = {219EC965-228A-1824-174D-96449D05F88A}
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782} = {9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}
+		{245603E3-F580-41A5-9632-B25FE3372CBF} = {245603E3-F580-41A5-9632-B25FE3372CBF}
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16} = {C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_opus_decode", "test_opus_decode.vcxproj", "{8578322A-1883-486B-B6FA-E0094B65C9F2}"
+	ProjectSection(ProjectDependencies) = postProject
+		{219EC965-228A-1824-174D-96449D05F88A} = {219EC965-228A-1824-174D-96449D05F88A}
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782} = {9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}
+		{245603E3-F580-41A5-9632-B25FE3372CBF} = {245603E3-F580-41A5-9632-B25FE3372CBF}
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16} = {C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_opus_encode", "test_opus_encode.vcxproj", "{84DAA768-1A38-4312-BB61-4C78BB59E5B8}"
+	ProjectSection(ProjectDependencies) = postProject
+		{219EC965-228A-1824-174D-96449D05F88A} = {219EC965-228A-1824-174D-96449D05F88A}
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782} = {9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}
+		{245603E3-F580-41A5-9632-B25FE3372CBF} = {245603E3-F580-41A5-9632-B25FE3372CBF}
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16} = {C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "silk_float", "silk_float.vcxproj", "{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "silk_common", "silk_common.vcxproj", "{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "silk_fixed", "silk_fixed.vcxproj", "{8484C90D-1561-402F-A91D-2DB10F8C5171}"
+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
+		{219EC965-228A-1824-174D-96449D05F88A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{219EC965-228A-1824-174D-96449D05F88A}.Debug|Win32.Build.0 = Debug|Win32
+		{219EC965-228A-1824-174D-96449D05F88A}.Debug|x64.ActiveCfg = Debug|x64
+		{219EC965-228A-1824-174D-96449D05F88A}.Debug|x64.Build.0 = Debug|x64
+		{219EC965-228A-1824-174D-96449D05F88A}.Release|Win32.ActiveCfg = Release|Win32
+		{219EC965-228A-1824-174D-96449D05F88A}.Release|Win32.Build.0 = Release|Win32
+		{219EC965-228A-1824-174D-96449D05F88A}.Release|x64.ActiveCfg = Release|x64
+		{219EC965-228A-1824-174D-96449D05F88A}.Release|x64.Build.0 = Release|x64
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Debug|Win32.ActiveCfg = Debug|Win32
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Debug|Win32.Build.0 = Debug|Win32
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Debug|x64.ActiveCfg = Debug|x64
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Debug|x64.Build.0 = Debug|x64
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Release|Win32.ActiveCfg = Release|Win32
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Release|Win32.Build.0 = Release|Win32
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Release|x64.ActiveCfg = Release|x64
+		{245603E3-F580-41A5-9632-B25FE3372CBF}.Release|x64.Build.0 = Release|x64
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Debug|Win32.Build.0 = Debug|Win32
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Debug|x64.ActiveCfg = Debug|x64
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Debug|x64.Build.0 = Debug|x64
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Release|Win32.ActiveCfg = Release|Win32
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Release|Win32.Build.0 = Release|Win32
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Release|x64.ActiveCfg = Release|x64
+		{016C739D-6389-43BF-8D88-24B2BF6F620F}.Release|x64.Build.0 = Release|x64
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Debug|Win32.Build.0 = Debug|Win32
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Debug|x64.ActiveCfg = Debug|x64
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Debug|x64.Build.0 = Debug|x64
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Release|Win32.ActiveCfg = Release|Win32
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Release|Win32.Build.0 = Release|Win32
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Release|x64.ActiveCfg = Release|x64
+		{1D257A17-D254-42E5-82D6-1C87A6EC775A}.Release|x64.Build.0 = Release|x64
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Debug|Win32.Build.0 = Debug|Win32
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Debug|x64.ActiveCfg = Debug|x64
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Debug|x64.Build.0 = Debug|x64
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Release|Win32.ActiveCfg = Release|Win32
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Release|Win32.Build.0 = Release|Win32
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Release|x64.ActiveCfg = Release|x64
+		{8578322A-1883-486B-B6FA-E0094B65C9F2}.Release|x64.Build.0 = Release|x64
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Debug|Win32.ActiveCfg = Debug|Win32
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Debug|Win32.Build.0 = Debug|Win32
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Debug|x64.ActiveCfg = Debug|x64
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Debug|x64.Build.0 = Debug|x64
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Release|Win32.ActiveCfg = Release|Win32
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Release|Win32.Build.0 = Release|Win32
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Release|x64.ActiveCfg = Release|x64
+		{84DAA768-1A38-4312-BB61-4C78BB59E5B8}.Release|x64.Build.0 = Release|x64
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Debug|Win32.ActiveCfg = Debug|Win32
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Debug|Win32.Build.0 = Debug|Win32
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Debug|x64.ActiveCfg = Debug|x64
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Debug|x64.Build.0 = Debug|x64
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Release|Win32.ActiveCfg = Release|Win32
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Release|Win32.Build.0 = Release|Win32
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Release|x64.ActiveCfg = Release|x64
+		{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}.Release|x64.Build.0 = Release|x64
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Debug|Win32.ActiveCfg = Debug|Win32
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Debug|Win32.Build.0 = Debug|Win32
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Debug|x64.ActiveCfg = Debug|x64
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Debug|x64.Build.0 = Debug|x64
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Release|Win32.ActiveCfg = Release|Win32
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Release|Win32.Build.0 = Release|Win32
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Release|x64.ActiveCfg = Release|x64
+		{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}.Release|x64.Build.0 = Release|x64
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Debug|Win32.Build.0 = Debug|Win32
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Debug|x64.ActiveCfg = Debug|x64
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Debug|x64.Build.0 = Debug|x64
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Release|Win32.ActiveCfg = Release|Win32
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Release|Win32.Build.0 = Release|Win32
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Release|x64.ActiveCfg = Release|x64
+		{8484C90D-1561-402F-A91D-2DB10F8C5171}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/win32/VS2010/opus.vcxproj b/win32/VS2010/opus.vcxproj
new file mode 100644
index 0000000..aa89a1e
--- /dev/null
+++ b/win32/VS2010/opus.vcxproj
@@ -0,0 +1,239 @@
+<?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">
+    <Keyword>Win32Proj</Keyword>
+    <ProjectName>opus</ProjectName>
+    <ProjectGuid>{219EC965-228A-1824-174D-96449D05F88A}</ProjectGuid>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+  </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>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <LinkIncremental>true</LinkIncremental>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LinkIncremental>false</LinkIncremental>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <LinkIncremental>false</LinkIncremental>
+    <CustomBuildBeforeTargets>
+    </CustomBuildBeforeTargets>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk;../../celt;../../win32;../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <Optimization>Disabled</Optimization>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <TargetMachine>MachineX86</TargetMachine>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <AdditionalLibraryDirectories>$(SolutionDir)$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>celt.lib;silk_common.lib;silk_fixed.lib;silk_float.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;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk;../../celt;../../win32;../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <Optimization>Disabled</Optimization>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <AdditionalLibraryDirectories>$(SolutionDir)$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>celt.lib;silk_common.lib;silk_fixed.lib;silk_float.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;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk;../../celt;../../win32;../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <TargetMachine>MachineX86</TargetMachine>
+      <GenerateDebugInformation>false</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>celt.lib;silk_common.lib;silk_fixed.lib;silk_float.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;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalLibraryDirectories>$(SolutionDir)$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <LinkStatus>false</LinkStatus>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk;../../celt;../../win32;../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>false</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>celt.lib;silk_common.lib;silk_fixed.lib;silk_float.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;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalLibraryDirectories>$(SolutionDir)$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <LinkStatus>false</LinkStatus>
+    </Link>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\celt\arch.h" />
+    <ClInclude Include="..\..\celt\celt.h" />
+    <ClInclude Include="..\..\celt\entdec.h" />
+    <ClInclude Include="..\..\celt\entenc.h" />
+    <ClInclude Include="..\..\celt\float_cast.h" />
+    <ClInclude Include="..\..\celt\os_support.h" />
+    <ClInclude Include="..\..\celt\stack_alloc.h" />
+    <ClInclude Include="..\..\include\opus.h" />
+    <ClInclude Include="..\..\include\opus_defines.h" />
+    <ClInclude Include="..\..\include\opus_types.h" />
+    <ClInclude Include="..\..\include\opus_multistream.h" />
+    <ClInclude Include="..\..\win32\config.h" />
+    <ClInclude Include="..\..\src\analysis.h" />
+    <ClInclude Include="..\..\src\mlp.h" />
+    <ClInclude Include="..\..\src\opus_private.h" />
+    <ClInclude Include="..\..\src\tansig_table.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\src\analysis.c" />
+    <ClCompile Include="..\..\src\mlp.c" />
+    <ClCompile Include="..\..\src\mlp_data.c" />
+    <ClCompile Include="..\..\src\opus.c" />
+    <ClCompile Include="..\..\src\opus_compare.c" />
+    <ClCompile Include="..\..\src\opus_decoder.c" />
+    <ClCompile Include="..\..\src\opus_encoder.c" />
+    <ClCompile Include="..\..\src\opus_multistream.c" />
+    <ClCompile Include="..\..\src\opus_multistream_decoder.c" />
+    <ClCompile Include="..\..\src\opus_multistream_encoder.c" />
+    <ClCompile Include="..\..\src\repacketizer.c" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
diff --git a/win32/VS2010/opus.vcxproj.filters b/win32/VS2010/opus.vcxproj.filters
new file mode 100644
index 0000000..7160778
--- /dev/null
+++ b/win32/VS2010/opus.vcxproj.filters
@@ -0,0 +1,102 @@
+<?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</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\celt\arch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\celt.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\entdec.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\entenc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\float_cast.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\os_support.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\celt\stack_alloc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\include\opus.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\include\opus_defines.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\include\opus_types.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\include\opus_multistream.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\win32\config.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\src\analysis.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\src\mlp.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\src\opus_private.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\src\tansig_table.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\src\opus.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\opus_compare.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\opus_decoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\opus_encoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\opus_multistream.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\opus_multistream_decoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\opus_multistream_encoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\repacketizer.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\analysis.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\mlp.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\mlp_data.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
diff --git a/win32/VS2010/opus_demo.vcxproj b/win32/VS2010/opus_demo.vcxproj
new file mode 100644
index 0000000..9cc081f
--- /dev/null
+++ b/win32/VS2010/opus_demo.vcxproj
@@ -0,0 +1,156 @@
+<?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>{016C739D-6389-43BF-8D88-24B2BF6F620F}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>opus_demo</RootNamespace>
+  </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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../silk;../celt;../win32;../include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(SolutionDir)$(Configuration)\opus.lib;$(SolutionDir)$(Configuration)\celt.lib;$(SolutionDir)$(Configuration)\silk_common.lib;$(SolutionDir)$(Configuration)\silk_float.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../silk;../celt;../win32;../include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(SolutionDir)$(Configuration)\opus.lib;$(SolutionDir)$(Configuration)\celt.lib;$(SolutionDir)$(Configuration)\silk_common.lib;$(SolutionDir)$(Configuration)\silk_float.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>../silk;../celt;../win32;../include;</AdditionalIncludeDirectories>
+      <MultiProcessorCompilation>true</MultiProcessorCompilation>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(SolutionDir)$(Configuration)\opus.lib;$(SolutionDir)$(Configuration)\celt.lib;$(SolutionDir)$(Configuration)\silk_common.lib;$(SolutionDir)$(Configuration)\silk_float.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>../silk;../celt;../win32;../include;</AdditionalIncludeDirectories>
+      <MultiProcessorCompilation>true</MultiProcessorCompilation>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(SolutionDir)$(Configuration)\opus.lib;$(SolutionDir)$(Configuration)\celt.lib;$(SolutionDir)$(Configuration)\silk_common.lib;$(SolutionDir)$(Configuration)\silk_float.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/opus_demo.vcxproj.filters b/win32/VS2010/opus_demo.vcxproj.filters
new file mode 100644
index 0000000..d7ef6a1
--- /dev/null
+++ b/win32/VS2010/opus_demo.vcxproj.filters
@@ -0,0 +1,17 @@
+<?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>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/silk_common.vcxproj b/win32/VS2010/silk_common.vcxproj
new file mode 100644
index 0000000..9cf5f48
--- /dev/null
+++ b/win32/VS2010/silk_common.vcxproj
@@ -0,0 +1,318 @@
+<?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>{C303D2FC-FF97-49B8-9DDD-467B4C9A0B16}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>src_common</RootNamespace>
+    <ProjectName>silk_common</ProjectName>
+  </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>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <CustomBuildBeforeTargets>
+    </CustomBuildBeforeTargets>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk/float;../../win32;../../celt;../../include</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk/float;../../win32;../../celt;../../include</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk/float;../../win32;../../celt;../../include</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FloatingPointModel>Fast</FloatingPointModel>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk/float;../../win32;../../celt;../../include</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FloatingPointModel>Fast</FloatingPointModel>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\include\opus_types.h" />
+    <ClInclude Include="..\..\win32\config.h" />
+    <ClInclude Include="..\..\silk\control.h" />
+    <ClInclude Include="..\..\silk\debug.h" />
+    <ClInclude Include="..\..\silk\define.h" />
+    <ClInclude Include="..\..\silk\errors.h" />
+    <ClInclude Include="..\..\silk\Inlines.h" />
+    <ClInclude Include="..\..\silk\MacroCount.h" />
+    <ClInclude Include="..\..\silk\MacroDebug.h" />
+    <ClInclude Include="..\..\silk\macros.h" />
+    <ClInclude Include="..\..\silk\main.h" />
+    <ClInclude Include="..\..\silk\pitch_est_defines.h" />
+    <ClInclude Include="..\..\silk\PLC.h" />
+    <ClInclude Include="..\..\silk\resampler_private.h" />
+    <ClInclude Include="..\..\silk\resampler_rom.h" />
+    <ClInclude Include="..\..\silk\resampler_structs.h" />
+    <ClInclude Include="..\..\silk\API.h" />
+    <ClInclude Include="..\..\silk\SigProc_FIX.h" />
+    <ClInclude Include="..\..\silk\structs.h" />
+    <ClInclude Include="..\..\silk\tables.h" />
+    <ClInclude Include="..\..\silk\tuning_parameters.h" />
+    <ClInclude Include="..\..\silk\typedef.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\silk\A2NLSF.c" />
+    <ClCompile Include="..\..\silk\ana_filt_bank_1.c" />
+    <ClCompile Include="..\..\silk\biquad_alt.c" />
+    <ClCompile Include="..\..\silk\bwexpander.c" />
+    <ClCompile Include="..\..\silk\bwexpander_32.c" />
+    <ClCompile Include="..\..\silk\check_control_input.c" />
+    <ClCompile Include="..\..\silk\CNG.c" />
+    <ClCompile Include="..\..\silk\code_signs.c" />
+    <ClCompile Include="..\..\silk\control_audio_bandwidth.c" />
+    <ClCompile Include="..\..\silk\control_codec.c" />
+    <ClCompile Include="..\..\silk\control_SNR.c" />
+    <ClCompile Include="..\..\silk\debug.c" />
+    <ClCompile Include="..\..\silk\decoder_set_fs.c" />
+    <ClCompile Include="..\..\silk\decode_core.c" />
+    <ClCompile Include="..\..\silk\decode_frame.c" />
+    <ClCompile Include="..\..\silk\decode_indices.c" />
+    <ClCompile Include="..\..\silk\decode_parameters.c" />
+    <ClCompile Include="..\..\silk\decode_pitch.c" />
+    <ClCompile Include="..\..\silk\decode_pulses.c" />
+    <ClCompile Include="..\..\silk\dec_API.c" />
+    <ClCompile Include="..\..\silk\encode_indices.c" />
+    <ClCompile Include="..\..\silk\encode_pulses.c" />
+    <ClCompile Include="..\..\silk\enc_API.c" />
+    <ClCompile Include="..\..\silk\gain_quant.c" />
+    <ClCompile Include="..\..\silk\HP_variable_cutoff.c" />
+    <ClCompile Include="..\..\silk\init_decoder.c" />
+    <ClCompile Include="..\..\silk\init_encoder.c" />
+    <ClCompile Include="..\..\silk\inner_prod_aligned.c" />
+    <ClCompile Include="..\..\silk\interpolate.c" />
+    <ClCompile Include="..\..\silk\lin2log.c" />
+    <ClCompile Include="..\..\silk\log2lin.c" />
+    <ClCompile Include="..\..\silk\LPC_analysis_filter.c" />
+    <ClCompile Include="..\..\silk\LPC_inv_pred_gain.c" />
+    <ClCompile Include="..\..\silk\LP_variable_cutoff.c" />
+    <ClCompile Include="..\..\silk\NLSF2A.c" />
+    <ClCompile Include="..\..\silk\NLSF_decode.c" />
+    <ClCompile Include="..\..\silk\NLSF_del_dec_quant.c" />
+    <ClCompile Include="..\..\silk\NLSF_encode.c" />
+    <ClCompile Include="..\..\silk\NLSF_stabilize.c" />
+    <ClCompile Include="..\..\silk\NLSF_unpack.c" />
+    <ClCompile Include="..\..\silk\NLSF_VQ.c" />
+    <ClCompile Include="..\..\silk\NLSF_VQ_weights_laroia.c" />
+    <ClCompile Include="..\..\silk\NSQ.c" />
+    <ClCompile Include="..\..\silk\NSQ_del_dec.c" />
+    <ClCompile Include="..\..\silk\pitch_est_tables.c" />
+    <ClCompile Include="..\..\silk\PLC.c" />
+    <ClCompile Include="..\..\silk\process_NLSFs.c" />
+    <ClCompile Include="..\..\silk\quant_LTP_gains.c" />
+    <ClCompile Include="..\..\silk\resampler.c" />
+    <ClCompile Include="..\..\silk\resampler_down2.c" />
+    <ClCompile Include="..\..\silk\resampler_down2_3.c" />
+    <ClCompile Include="..\..\silk\resampler_private_AR2.c" />
+    <ClCompile Include="..\..\silk\resampler_private_down_FIR.c" />
+    <ClCompile Include="..\..\silk\resampler_private_IIR_FIR.c" />
+    <ClCompile Include="..\..\silk\resampler_private_up2_HQ.c" />
+    <ClCompile Include="..\..\silk\resampler_rom.c" />
+    <ClCompile Include="..\..\silk\shell_coder.c" />
+    <ClCompile Include="..\..\silk\sigm_Q15.c" />
+    <ClCompile Include="..\..\silk\sort.c" />
+    <ClCompile Include="..\..\silk\stereo_decode_pred.c" />
+    <ClCompile Include="..\..\silk\stereo_encode_pred.c" />
+    <ClCompile Include="..\..\silk\stereo_find_predictor.c" />
+    <ClCompile Include="..\..\silk\stereo_LR_to_MS.c" />
+    <ClCompile Include="..\..\silk\stereo_MS_to_LR.c" />
+    <ClCompile Include="..\..\silk\stereo_quant_pred.c" />
+    <ClCompile Include="..\..\silk\sum_sqr_shift.c" />
+    <ClCompile Include="..\..\silk\tables_gain.c" />
+    <ClCompile Include="..\..\silk\tables_LTP.c" />
+    <ClCompile Include="..\..\silk\tables_NLSF_CB_NB_MB.c" />
+    <ClCompile Include="..\..\silk\tables_NLSF_CB_WB.c" />
+    <ClCompile Include="..\..\silk\tables_other.c" />
+    <ClCompile Include="..\..\silk\tables_pitch_lag.c" />
+    <ClCompile Include="..\..\silk\tables_pulses_per_block.c" />
+    <ClCompile Include="..\..\silk\table_LSF_cos.c" />
+    <ClCompile Include="..\..\silk\VAD.c" />
+    <ClCompile Include="..\..\silk\VQ_WMat_EC.c" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
diff --git a/win32/VS2010/silk_common.vcxproj.filters b/win32/VS2010/silk_common.vcxproj.filters
new file mode 100644
index 0000000..30db48e
--- /dev/null
+++ b/win32/VS2010/silk_common.vcxproj.filters
@@ -0,0 +1,315 @@
+<?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>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\include\opus_types.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\win32\config.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\control.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\debug.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\define.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\errors.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\Inlines.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\MacroCount.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\MacroDebug.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\macros.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\main.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\pitch_est_defines.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\PLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\resampler_private.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\resampler_rom.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\resampler_structs.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\API.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\SigProc_FIX.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\structs.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\tables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\tuning_parameters.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\silk\typedef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\silk\VQ_WMat_EC.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\A2NLSF.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\ana_filt_bank_1.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\biquad_alt.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\bwexpander.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\bwexpander_32.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\check_control_input.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\CNG.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\code_signs.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\control_audio_bandwidth.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\control_codec.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\control_SNR.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\debug.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\dec_API.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decode_core.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decode_frame.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decode_indices.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decode_parameters.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decode_pitch.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decode_pulses.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\decoder_set_fs.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\enc_API.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\encode_indices.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\encode_pulses.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\gain_quant.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\HP_variable_cutoff.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\init_decoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\init_encoder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\inner_prod_aligned.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\interpolate.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\lin2log.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\log2lin.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\LP_variable_cutoff.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\LPC_analysis_filter.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\LPC_inv_pred_gain.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_decode.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_del_dec_quant.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_encode.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_stabilize.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_unpack.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_VQ.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF_VQ_weights_laroia.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NLSF2A.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NSQ.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\NSQ_del_dec.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\pitch_est_tables.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\PLC.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\process_NLSFs.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\quant_LTP_gains.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_down2.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_down2_3.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_private_AR2.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_private_down_FIR.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_private_IIR_FIR.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_private_up2_HQ.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\resampler_rom.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\shell_coder.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\sigm_Q15.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\sort.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\stereo_decode_pred.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\stereo_encode_pred.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\stereo_find_predictor.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\stereo_LR_to_MS.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\stereo_MS_to_LR.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\stereo_quant_pred.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\sum_sqr_shift.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\table_LSF_cos.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_gain.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_LTP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_NLSF_CB_NB_MB.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_NLSF_CB_WB.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_other.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_pitch_lag.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\tables_pulses_per_block.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\VAD.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
diff --git a/win32/VS2010/silk_fixed.vcxproj b/win32/VS2010/silk_fixed.vcxproj
new file mode 100644
index 0000000..5ea1a91
--- /dev/null
+++ b/win32/VS2010/silk_fixed.vcxproj
@@ -0,0 +1,198 @@
+<?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>{8484C90D-1561-402F-A91D-2DB10F8C5171}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>src_FIX</RootNamespace>
+    <ProjectName>silk_fixed</ProjectName>
+  </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>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/fixed;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\include\opus_types.h" />
+    <ClInclude Include="..\..\win32\config.h" />
+    <ClInclude Include="..\..\silk\SigProc_FIX.h" />
+    <ClInclude Include="..\..\silk\fixed\main_FIX.h" />
+    <ClInclude Include="..\..\silk\fixed\structs_FIX.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\silk\fixed\apply_sine_window_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\autocorr_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\burg_modified_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\corrMatrix_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\encode_frame_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\find_LPC_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\find_LTP_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\find_pitch_lags_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\find_pred_coefs_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\k2a_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\k2a_Q16_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\LTP_analysis_filter_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\LTP_scale_ctrl_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\noise_shape_analysis_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\pitch_analysis_core_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\prefilter_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\process_gains_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\regularize_correlations_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\residual_energy16_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\residual_energy_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\schur64_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\schur_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\solve_LS_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\vector_ops_FIX.c" />
+    <ClCompile Include="..\..\silk\fixed\warped_autocorrelation_FIX.c" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
diff --git a/win32/VS2010/silk_fixed.vcxproj.filters b/win32/VS2010/silk_fixed.vcxproj.filters
new file mode 100644
index 0000000..6897930
--- /dev/null
+++ b/win32/VS2010/silk_fixed.vcxproj.filters
@@ -0,0 +1,111 @@
+<?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>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\win32\config.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="main_FIX.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\SigProc_FIX.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="structs_FIX.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\include\opus_types.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\silk\fixed\LTP_scale_ctrl_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\noise_shape_analysis_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\pitch_analysis_core_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\prefilter_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\process_gains_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\regularize_correlations_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\residual_energy_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\residual_energy16_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\schur_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\schur64_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\solve_LS_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\vector_ops_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\warped_autocorrelation_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\apply_sine_window_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\autocorr_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\burg_modified_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\corrMatrix_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\encode_frame_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\find_LPC_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\find_LTP_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\find_pitch_lags_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\find_pred_coefs_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\k2a_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\k2a_Q16_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\fixed\LTP_analysis_filter_FIX.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/silk_float.vcxproj b/win32/VS2010/silk_float.vcxproj
new file mode 100644
index 0000000..8c38795
--- /dev/null
+++ b/win32/VS2010/silk_float.vcxproj
@@ -0,0 +1,253 @@
+<?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>{9C4961D2-5DDB-40C7-9BE8-CA918DC4E782}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>src_FLP</RootNamespace>
+    <ProjectName>silk_float</ProjectName>
+  </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>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <CustomBuildBeforeTargets>Compile</CustomBuildBeforeTargets>
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/float;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/float;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/float;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;WIN64;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../silk/float;../../silk;../../win32;../../celt;../../include;../win32</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+    <Lib>
+      <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+    </Lib>
+    <PreBuildEvent>
+      <Command>"$(ProjectDir)..\..\win32\genversion.bat" "$(ProjectDir)..\..\win32\version.h" PACKAGE_VERSION</Command>
+      <Message>Generating version.h</Message>
+    </PreBuildEvent>
+    <CustomBuildStep>
+      <Command>
+      </Command>
+    </CustomBuildStep>
+    <CustomBuildStep>
+      <Outputs>
+      </Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\include\opus_types.h" />
+    <ClInclude Include="..\..\win32\config.h" />
+    <ClInclude Include="..\..\silk\float\main_FLP.h" />
+    <ClInclude Include="..\..\silk\float\SigProc_FLP.h" />
+    <ClInclude Include="..\..\silk\float\structs_FLP.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\silk\float\apply_sine_window_FLP.c" />
+    <ClCompile Include="..\..\silk\float\autocorrelation_FLP.c" />
+    <ClCompile Include="..\..\silk\float\burg_modified_FLP.c" />
+    <ClCompile Include="..\..\silk\float\bwexpander_FLP.c" />
+    <ClCompile Include="..\..\silk\float\corrMatrix_FLP.c" />
+    <ClCompile Include="..\..\silk\float\encode_frame_FLP.c" />
+    <ClCompile Include="..\..\silk\float\energy_FLP.c" />
+    <ClCompile Include="..\..\silk\float\find_LPC_FLP.c" />
+    <ClCompile Include="..\..\silk\float\find_LTP_FLP.c" />
+    <ClCompile Include="..\..\silk\float\find_pitch_lags_FLP.c" />
+    <ClCompile Include="..\..\silk\float\find_pred_coefs_FLP.c" />
+    <ClCompile Include="..\..\silk\float\inner_product_FLP.c" />
+    <ClCompile Include="..\..\silk\float\k2a_FLP.c" />
+    <ClCompile Include="..\..\silk\float\levinsondurbin_FLP.c" />
+    <ClCompile Include="..\..\silk\float\LPC_analysis_filter_FLP.c" />
+    <ClCompile Include="..\..\silk\float\LPC_inv_pred_gain_FLP.c" />
+    <ClCompile Include="..\..\silk\float\LTP_analysis_filter_FLP.c" />
+    <ClCompile Include="..\..\silk\float\LTP_scale_ctrl_FLP.c" />
+    <ClCompile Include="..\..\silk\float\noise_shape_analysis_FLP.c" />
+    <ClCompile Include="..\..\silk\float\pitch_analysis_core_FLP.c" />
+    <ClCompile Include="..\..\silk\float\prefilter_FLP.c" />
+    <ClCompile Include="..\..\silk\float\process_gains_FLP.c" />
+    <ClCompile Include="..\..\silk\float\regularize_correlations_FLP.c" />
+    <ClCompile Include="..\..\silk\float\residual_energy_FLP.c" />
+    <ClCompile Include="..\..\silk\float\scale_copy_vector_FLP.c" />
+    <ClCompile Include="..\..\silk\float\scale_vector_FLP.c" />
+    <ClCompile Include="..\..\silk\float\schur_FLP.c" />
+    <ClCompile Include="..\..\silk\float\solve_LS_FLP.c" />
+    <ClCompile Include="..\..\silk\float\sort_FLP.c" />
+    <ClCompile Include="..\..\silk\float\warped_autocorrelation_FLP.c" />
+    <ClCompile Include="..\..\silk\float\wrappers_FLP.c" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
diff --git a/win32/VS2010/silk_float.vcxproj.filters b/win32/VS2010/silk_float.vcxproj.filters
new file mode 100644
index 0000000..a7088b2
--- /dev/null
+++ b/win32/VS2010/silk_float.vcxproj.filters
@@ -0,0 +1,129 @@
+<?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>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\include\opus_types.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\win32\config.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="main_FLP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="SigProc_FLP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="structs_FLP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\silk\float\scale_vector_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\schur_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\solve_LS_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\sort_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\warped_autocorrelation_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\wrappers_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\apply_sine_window_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\autocorrelation_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\burg_modified_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\bwexpander_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\corrMatrix_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\encode_frame_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\energy_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\find_LPC_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\find_LTP_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\find_pitch_lags_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\find_pred_coefs_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\inner_product_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\k2a_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\levinsondurbin_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\LPC_analysis_filter_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\LPC_inv_pred_gain_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\LTP_analysis_filter_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\LTP_scale_ctrl_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\noise_shape_analysis_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\pitch_analysis_core_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\prefilter_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\process_gains_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\regularize_correlations_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\residual_energy_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\silk\float\scale_copy_vector_FLP.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/test_opus_api.vcxproj b/win32/VS2010/test_opus_api.vcxproj
new file mode 100644
index 0000000..bf42a8f
--- /dev/null
+++ b/win32/VS2010/test_opus_api.vcxproj
@@ -0,0 +1,157 @@
+<?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>
+  <ItemGroup>
+    <ClCompile Include="..\..\tests\test_opus_api.c" />
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{1D257A17-D254-42E5-82D6-1C87A6EC775A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>test_opus_api</RootNamespace>
+  </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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/test_opus_api.vcxproj.filters b/win32/VS2010/test_opus_api.vcxproj.filters
new file mode 100644
index 0000000..383d19f
--- /dev/null
+++ b/win32/VS2010/test_opus_api.vcxproj.filters
@@ -0,0 +1,14 @@
+<?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>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\tests\test_opus_api.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/test_opus_decode.vcxproj b/win32/VS2010/test_opus_decode.vcxproj
new file mode 100644
index 0000000..3452331
--- /dev/null
+++ b/win32/VS2010/test_opus_decode.vcxproj
@@ -0,0 +1,161 @@
+<?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>
+  <ItemGroup>
+    <ClCompile Include="..\..\tests\test_opus_decode.c" />
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{8578322A-1883-486B-B6FA-E0094B65C9F2}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>test_opus_api</RootNamespace>
+  </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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
diff --git a/win32/VS2010/test_opus_decode.vcxproj.filters b/win32/VS2010/test_opus_decode.vcxproj.filters
new file mode 100644
index 0000000..3036a4e
--- /dev/null
+++ b/win32/VS2010/test_opus_decode.vcxproj.filters
@@ -0,0 +1,14 @@
+<?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>{4a0dd677-931f-4728-afe5-b761149fc7eb}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\tests\test_opus_decode.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/VS2010/test_opus_encode.vcxproj b/win32/VS2010/test_opus_encode.vcxproj
new file mode 100644
index 0000000..d2ede27
--- /dev/null
+++ b/win32/VS2010/test_opus_encode.vcxproj
@@ -0,0 +1,161 @@
+<?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>
+  <ItemGroup>
+    <ClCompile Include="..\..\tests\test_opus_encode.c" />
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{84DAA768-1A38-4312-BB61-4C78BB59E5B8}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>test_opus_api</RootNamespace>
+  </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'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
+    <OutDir>$(Platform)\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>HAVE_CONFIG_H;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>..\..\silk;..\..\celt;..\;..\..\include;</AdditionalIncludeDirectories>
+      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>$(Platform)\$(Configuration)\opus.lib;$(Platform)\$(Configuration)\celt.lib;$(Platform)\$(Configuration)\silk_common.lib;$(Platform)\$(Configuration)\silk_float.lib</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
diff --git a/win32/VS2010/test_opus_encode.vcxproj.filters b/win32/VS2010/test_opus_encode.vcxproj.filters
new file mode 100644
index 0000000..84ef445
--- /dev/null
+++ b/win32/VS2010/test_opus_encode.vcxproj.filters
@@ -0,0 +1,14 @@
+<?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>{546c8d9a-103e-4f78-972b-b44e8d3c8aba}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\tests\test_opus_encode.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/win32/config.h b/win32/config.h
index 8450d23..6cf0cad 100644
--- a/win32/config.h
+++ b/win32/config.h
@@ -12,7 +12,7 @@
 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”
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
@@ -28,8 +28,6 @@
 #ifndef CONFIG_H
 #define CONFIG_H
 
-#define CELT_BUILD            1
-
 #define inline __inline
 
 #define USE_ALLOCA            1
@@ -39,11 +37,11 @@
 
 #define OPUS_BUILD            1
 
-/* Get rid of the CELT VS compile warnings */
-#if 1
-#pragma warning(disable : 4996)/* This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. */
+/* Enable SSE functions, if compiled with SSE/SSE2 (note that AMD64 implies SSE2) */
+#if defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))
+#define __SSE__               1
 #endif
 
 #include "version.h"
 
-#endif CONFIG_H
+#endif /* CONFIG_H */