[SCM] ffms2/upstream: Imported Upstream version 2.17

siretart at users.alioth.debian.org siretart at users.alioth.debian.org
Mon Jan 23 13:08:43 UTC 2012


The following commit has been merged in the upstream branch:
commit 2da154392c746ce9064f9e37dc4ef1cfd3d9b209
Author: Reinhard Tartler <siretart at tauware.de>
Date:   Mon Jan 23 10:18:41 2012 +0100

    Imported Upstream version 2.17

diff --git a/Makefile.am b/Makefile.am
index fbdf08a..ae1c8dc 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -6,13 +6,15 @@ pkgconfig_DATA = ffms2.pc
 
 dist_doc_DATA = doc/ffms2-api.html doc/ffms2-changelog.html doc/style.css
 
-INCLUDES = -I. -I$(top_srcdir)/include -I$(top_srcdir)/src/config @FFMPEG_CFLAGS@ @POSTPROC_CFLAGS@ @ZLIB_CPPFLAGS@
+INCLUDES = -I. -I$(top_srcdir)/include -I$(top_srcdir)/src/config @LIBAV_CFLAGS@ @ZLIB_CPPFLAGS@ -include config.h
 
 lib_LTLIBRARIES = src/core/libffms2.la
-src_core_libffms2_la_LIBADD = @FFMPEG_LIBS@ @POSTPROC_LIBS@ @ZLIB_LDFLAGS@ -lz @LTUNDEF@
+src_core_libffms2_la_LIBADD = @LIBAV_LIBS@ @ZLIB_LDFLAGS@ -lz @LTUNDEF@
 src_core_libffms2_la_SOURCES = \
 	src/core/audiosource.h \
 	src/core/audiosource.cpp \
+	src/core/codectype.h \
+	src/core/codectype.cpp \
 	src/core/coparser.h \
 	src/core/ffms.cpp \
 	src/core/guids.h \
diff --git a/Makefile.in b/Makefile.in
index f5d4f3e..8bb40c9 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -88,7 +88,7 @@ LTLIBRARIES = $(lib_LTLIBRARIES)
 src_core_libffms2_la_DEPENDENCIES =
 am__dirstamp = $(am__leading_dot)dirstamp
 am_src_core_libffms2_la_OBJECTS = src/core/audiosource.lo \
-	src/core/ffms.lo src/core/haaliaudio.lo \
+	src/core/codectype.lo src/core/ffms.lo src/core/haaliaudio.lo \
 	src/core/haaliindexer.lo src/core/haalivideo.lo \
 	src/core/indexing.lo src/core/lavfaudio.lo \
 	src/core/lavfindexer.lo src/core/lavfvideo.lo \
@@ -175,8 +175,6 @@ EGREP = @EGREP@
 EXEEXT = @EXEEXT@
 F77 = @F77@
 FC = @FC@
-FFMPEG_CFLAGS = @FFMPEG_CFLAGS@
-FFMPEG_LIBS = @FFMPEG_LIBS@
 FFMS_VERSION = @FFMS_VERSION@
 FGREP = @FGREP@
 GREP = @GREP@
@@ -187,6 +185,8 @@ INSTALL_SCRIPT = @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
 LD = @LD@
 LDFLAGS = @LDFLAGS@
+LIBAV_CFLAGS = @LIBAV_CFLAGS@
+LIBAV_LIBS = @LIBAV_LIBS@
 LIBOBJS = @LIBOBJS@
 LIBS = @LIBS@
 LIBTOOL = @LIBTOOL@
@@ -218,8 +218,6 @@ PATH_SEPARATOR = @PATH_SEPARATOR@
 PKG_CONFIG = @PKG_CONFIG@
 PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
 PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-POSTPROC_CFLAGS = @POSTPROC_CFLAGS@
-POSTPROC_LIBS = @POSTPROC_LIBS@
 Q = @Q@
 RANLIB = @RANLIB@
 SED = @SED@
@@ -273,7 +271,6 @@ mkdir_p = @mkdir_p@
 oldincludedir = @oldincludedir@
 pdfdir = @pdfdir@
 pkgconfigdir = $(libdir)/pkgconfig
-postproc = @postproc@
 prefix = @prefix@
 program_transform_name = @program_transform_name@
 psdir = @psdir@
@@ -290,12 +287,14 @@ ACLOCAL_AMFLAGS = -I m4
 AUTOMAKE_OPTIONS = foreign
 pkgconfig_DATA = ffms2.pc
 dist_doc_DATA = doc/ffms2-api.html doc/ffms2-changelog.html doc/style.css
-INCLUDES = -I. -I$(top_srcdir)/include -I$(top_srcdir)/src/config @FFMPEG_CFLAGS@ @POSTPROC_CFLAGS@ @ZLIB_CPPFLAGS@
+INCLUDES = -I. -I$(top_srcdir)/include -I$(top_srcdir)/src/config @LIBAV_CFLAGS@ @ZLIB_CPPFLAGS@ -include config.h
 lib_LTLIBRARIES = src/core/libffms2.la
-src_core_libffms2_la_LIBADD = @FFMPEG_LIBS@ @POSTPROC_LIBS@ @ZLIB_LDFLAGS@ -lz @LTUNDEF@
+src_core_libffms2_la_LIBADD = @LIBAV_LIBS@ @ZLIB_LDFLAGS@ -lz @LTUNDEF@
 src_core_libffms2_la_SOURCES = \
 	src/core/audiosource.h \
 	src/core/audiosource.cpp \
+	src/core/codectype.h \
+	src/core/codectype.cpp \
 	src/core/coparser.h \
 	src/core/ffms.cpp \
 	src/core/guids.h \
@@ -428,6 +427,8 @@ src/core/$(DEPDIR)/$(am__dirstamp):
 	@: > src/core/$(DEPDIR)/$(am__dirstamp)
 src/core/audiosource.lo: src/core/$(am__dirstamp) \
 	src/core/$(DEPDIR)/$(am__dirstamp)
+src/core/codectype.lo: src/core/$(am__dirstamp) \
+	src/core/$(DEPDIR)/$(am__dirstamp)
 src/core/ffms.lo: src/core/$(am__dirstamp) \
 	src/core/$(DEPDIR)/$(am__dirstamp)
 src/core/haaliaudio.lo: src/core/$(am__dirstamp) \
@@ -525,6 +526,8 @@ mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
 	-rm -f src/core/audiosource.$(OBJEXT)
 	-rm -f src/core/audiosource.lo
+	-rm -f src/core/codectype.$(OBJEXT)
+	-rm -f src/core/codectype.lo
 	-rm -f src/core/ffms.$(OBJEXT)
 	-rm -f src/core/ffms.lo
 	-rm -f src/core/haaliaudio.$(OBJEXT)
@@ -567,6 +570,7 @@ distclean-compile:
 	-rm -f *.tab.c
 
 @AMDEP_TRUE@@am__include@ @am__quote at src/core/$(DEPDIR)/audiosource.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at src/core/$(DEPDIR)/codectype.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at src/core/$(DEPDIR)/ffms.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at src/core/$(DEPDIR)/haaliaudio.Plo at am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote at src/core/$(DEPDIR)/haaliindexer.Plo at am__quote@
diff --git a/aclocal.m4 b/aclocal.m4
index 04b0f16..ad5f26a 100644
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -47,8 +47,7 @@ To do so, use the procedure documented by the package, typically `autoreconf'.])
 # ----------------------------------
 AC_DEFUN([PKG_PROG_PKG_CONFIG],
 [m4_pattern_forbid([^_?PKG_[A-Z_]+$])
-m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
-m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
+m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
 AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
 AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
 AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
@@ -94,8 +93,7 @@ m4_define([_PKG_CONFIG],
     pkg_cv_[]$1="$$1"
  elif test -n "$PKG_CONFIG"; then
     PKG_CHECK_EXISTS([$3],
-                     [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes ],
+                     [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
 		     [pkg_failed=yes])
  else
     pkg_failed=untried
@@ -143,9 +141,9 @@ if test $pkg_failed = yes; then
    	AC_MSG_RESULT([no])
         _PKG_SHORT_ERRORS_SUPPORTED
         if test $_pkg_short_errors_supported = yes; then
-	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
+	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "$2" 2>&1`
         else 
-	        $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
+	        $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors "$2" 2>&1`
         fi
 	# Put the nasty error message in config.log where it belongs
 	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
@@ -169,7 +167,7 @@ path to pkg-config.
 
 _PKG_TEXT
 
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl
+To get pkg-config, see <http://pkg-config.freedesktop.org/>.])dnl
         ])
 else
 	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
diff --git a/build-msvc/ffms2.vcproj b/build-msvc/ffms2.vcproj
index 0226ad0..2ff4a19 100644
--- a/build-msvc/ffms2.vcproj
+++ b/build-msvc/ffms2.vcproj
@@ -168,7 +168,7 @@
 			ConfigurationType="2"
 			InheritedPropertySheets=".\ffms2_include_dirs.vsprops"
 			CharacterSet="2"
-			WholeProgramOptimization="0"
+			WholeProgramOptimization="1"
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
@@ -189,14 +189,9 @@
 			<Tool
 				Name="VCCLCompilerTool"
 				Optimization="2"
-				InlineFunctionExpansion="2"
-				EnableIntrinsicFunctions="true"
-				FavorSizeOrSpeed="1"
 				OmitFramePointers="true"
 				PreprocessorDefinitions="FFMS_EXPORTS;FFMS_USE_POSTPROC;HAALISOURCE;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;_SCL_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS"
-				StringPooling="true"
 				RuntimeLibrary="0"
-				EnableFunctionLevelLinking="true"
 				WarningLevel="3"
 				SuppressStartupBanner="true"
 				DebugInformationFormat="3"
@@ -215,7 +210,7 @@
 				Name="VCLinkerTool"
 				Version=""
 				SuppressStartupBanner="true"
-				GenerateDebugInformation="false"
+				GenerateDebugInformation="true"
 				OptimizeReferences="2"
 				EnableCOMDATFolding="2"
 				TargetMachine="1"
@@ -249,7 +244,7 @@
 			ConfigurationType="2"
 			InheritedPropertySheets=".\ffms2_include_dirs.vsprops"
 			CharacterSet="2"
-			WholeProgramOptimization="0"
+			WholeProgramOptimization="1"
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
@@ -271,14 +266,9 @@
 			<Tool
 				Name="VCCLCompilerTool"
 				Optimization="2"
-				InlineFunctionExpansion="2"
-				EnableIntrinsicFunctions="true"
-				FavorSizeOrSpeed="1"
 				OmitFramePointers="true"
 				PreprocessorDefinitions="FFMS_EXPORTS;FFMS_USE_POSTPROC;HAALISOURCE;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;_SCL_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS"
-				StringPooling="true"
 				RuntimeLibrary="0"
-				EnableFunctionLevelLinking="true"
 				WarningLevel="3"
 				SuppressStartupBanner="true"
 				DebugInformationFormat="3"
@@ -297,7 +287,7 @@
 				Name="VCLinkerTool"
 				Version=""
 				SuppressStartupBanner="true"
-				GenerateDebugInformation="false"
+				GenerateDebugInformation="true"
 				OptimizeReferences="2"
 				EnableCOMDATFolding="2"
 				TargetMachine="17"
@@ -424,6 +414,13 @@
 			Name="Utils"
 			>
 			<File
+				RelativePath="..\src\core\codectype.cpp"
+				>
+			</File>			<File
+				RelativePath="..\src\core\codectype.h"
+				>
+			</File>			
+			<File
 				RelativePath="..\src\core\coparser.h"
 				>
 			</File>
diff --git a/build-msvc/ffms2.vcxproj b/build-msvc/ffms2.vcxproj
index 008edd6..0b578a2 100644
--- a/build-msvc/ffms2.vcxproj
+++ b/build-msvc/ffms2.vcxproj
@@ -26,7 +26,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>false</WholeProgramOptimization>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
@@ -35,7 +35,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>false</WholeProgramOptimization>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
@@ -97,6 +97,7 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+      <MultiProcessorCompilation>false</MultiProcessorCompilation>
     </ClCompile>
     <Link>
       <GenerateDebugInformation>true</GenerateDebugInformation>
@@ -109,27 +110,23 @@
     </PreBuildEvent>
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
       <PreprocessorDefinitions>FFMS_EXPORTS;FFMS_USE_POSTPROC;HAALISOURCE;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;_SCL_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
       <OmitFramePointers>true</OmitFramePointers>
-      <StringPooling>true</StringPooling>
+      <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
       <Version>
       </Version>
       <SuppressStartupBanner>true</SuppressStartupBanner>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
       <OptimizeReferences>true</OptimizeReferences>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <TargetMachine>MachineX86</TargetMachine>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
     </Link>
   </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
@@ -148,6 +145,7 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+      <MultiProcessorCompilation>false</MultiProcessorCompilation>
     </ClCompile>
     <Link>
       <GenerateDebugInformation>true</GenerateDebugInformation>
@@ -163,78 +161,76 @@
     </Midl>
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
       <PreprocessorDefinitions>FFMS_EXPORTS;FFMS_USE_POSTPROC;HAALISOURCE;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_DEPRECATE;_SCL_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
       <OmitFramePointers>true</OmitFramePointers>
-      <StringPooling>true</StringPooling>
+      <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
       <Version>
       </Version>
       <SuppressStartupBanner>true</SuppressStartupBanner>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
       <OptimizeReferences>true</OptimizeReferences>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <TargetMachine>MachineX64</TargetMachine>
     </Link>
   </ItemDefinitionGroup>
   <ItemGroup>
+    <ClCompile Include="..\src\avisynth\avisynth.cpp" />
+    <ClCompile Include="..\src\avisynth\avssources.cpp" />
+    <ClCompile Include="..\src\avisynth\avsutils.cpp" />
+    <ClCompile Include="..\src\avisynth\ffpp.cpp" />
+    <ClCompile Include="..\src\avisynth\ffswscale.cpp" />
+    <ClCompile Include="..\src\config\libs.cpp" />
     <ClCompile Include="..\src\core\audiosource.cpp" />
+    <ClCompile Include="..\src\core\codectype.cpp" />
+    <ClCompile Include="..\src\core\ffms.cpp" />
     <ClCompile Include="..\src\core\haaliaudio.cpp" />
-    <ClCompile Include="..\src\core\lavfaudio.cpp" />
-    <ClCompile Include="..\src\core\matroskaaudio.cpp" />
     <ClCompile Include="..\src\core\haaliindexer.cpp" />
+    <ClCompile Include="..\src\core\haalivideo.cpp" />
     <ClCompile Include="..\src\core\indexing.cpp" />
+    <ClCompile Include="..\src\core\lavfaudio.cpp" />
     <ClCompile Include="..\src\core\lavfindexer.cpp" />
-    <ClCompile Include="..\src\core\matroskaindexer.cpp" />
-    <ClCompile Include="..\src\core\haalivideo.cpp" />
     <ClCompile Include="..\src\core\lavfvideo.cpp" />
-    <ClCompile Include="..\src\core\matroskavideo.cpp" />
-    <ClCompile Include="..\src\core\videosource.cpp" />
-    <ClCompile Include="..\src\core\ffms.cpp" />
+    <ClCompile Include="..\src\core\matroskaaudio.cpp" />
+    <ClCompile Include="..\src\core\matroskaindexer.cpp" />
     <ClCompile Include="..\src\core\matroskaparser.c" />
+    <ClCompile Include="..\src\core\matroskavideo.cpp" />
     <ClCompile Include="..\src\core\numthreads.cpp" />
     <ClCompile Include="..\src\core\stdiostream.c" />
     <ClCompile Include="..\src\core\utils.cpp" />
+    <ClCompile Include="..\src\core\videosource.cpp" />
     <ClCompile Include="..\src\core\videoutils.cpp" />
     <ClCompile Include="..\src\core\wave64writer.cpp" />
-    <ClCompile Include="..\src\avisynth\avisynth.cpp" />
-    <ClCompile Include="..\src\avisynth\avssources.cpp" />
-    <ClCompile Include="..\src\avisynth\avsutils.cpp" />
-    <ClCompile Include="..\src\avisynth\ffpp.cpp" />
-    <ClCompile Include="..\src\avisynth\ffswscale.cpp" />
-    <ClCompile Include="..\src\config\libs.cpp" />
   </ItemGroup>
   <ItemGroup>
-    <ClInclude Include="..\src\core\audiosource.h" />
-    <ClInclude Include="..\src\core\indexing.h" />
-    <ClInclude Include="..\src\core\videosource.h" />
     <ClInclude Include="..\include\ffms.h" />
-    <ClInclude Include="..\src\core\coparser.h" />
     <ClInclude Include="..\include\ffmscompat.h" />
+    <ClInclude Include="..\src\avisynth\avisynth.h" />
+    <ClInclude Include="..\src\avisynth\avssources.h" />
+    <ClInclude Include="..\src\avisynth\avsutils.h" />
+    <ClInclude Include="..\src\avisynth\ffpp.h" />
+    <ClInclude Include="..\src\avisynth\ffswscale.h" />
+    <ClInclude Include="..\src\config\msvc-config.h" />
+    <ClInclude Include="..\src\core\audiosource.h" />
+    <ClInclude Include="..\src\core\codectype.h" />
+    <ClInclude Include="..\src\core\coparser.h" />
     <ClInclude Include="..\src\core\guids.h" />
+    <ClInclude Include="..\src\core\indexing.h" />
     <ClInclude Include="..\src\core\matroskaparser.h" />
     <ClInclude Include="..\src\core\numthreads.h" />
     <ClInclude Include="..\src\core\stdiostream.h" />
     <ClInclude Include="..\src\core\utils.h" />
+    <ClInclude Include="..\src\core\videosource.h" />
     <ClInclude Include="..\src\core\videoutils.h" />
     <ClInclude Include="..\src\core\wave64writer.h" />
-    <ClInclude Include="..\src\avisynth\avisynth.h" />
-    <ClInclude Include="..\src\avisynth\avssources.h" />
-    <ClInclude Include="..\src\avisynth\avsutils.h" />
-    <ClInclude Include="..\src\avisynth\ffpp.h" />
-    <ClInclude Include="..\src\avisynth\ffswscale.h" />
-    <ClInclude Include="..\src\config\msvc-config.h" />
   </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
-</Project>
\ No newline at end of file
+</Project>
diff --git a/build-msvc/ffms2.vcxproj.filters b/build-msvc/ffms2.vcxproj.filters
index bde55f4..55173ff 100644
--- a/build-msvc/ffms2.vcxproj.filters
+++ b/build-msvc/ffms2.vcxproj.filters
@@ -63,6 +63,9 @@
     <ClCompile Include="..\src\core\ffms.cpp">
       <Filter>API</Filter>
     </ClCompile>
+	<ClCompile Include="..\src\core\codectype.cpp">
+	  <Filter>Utils</Filter>
+	</ClCompile>
     <ClCompile Include="..\src\core\matroskaparser.c">
       <Filter>Utils</Filter>
     </ClCompile>
@@ -116,6 +119,9 @@
     <ClInclude Include="..\src\core\coparser.h">
       <Filter>Utils</Filter>
     </ClInclude>
+	<ClInclude Include="..\src\core\codectype.h">
+	  <Filter>Utils</Filter>
+	</ClInclude>
     <ClInclude Include="..\include\ffmscompat.h">
       <Filter>Utils</Filter>
     </ClInclude>
diff --git a/build-msvc/ffmsindex.vcproj b/build-msvc/ffmsindex.vcproj
index be472a0..805c31a 100644
--- a/build-msvc/ffmsindex.vcproj
+++ b/build-msvc/ffmsindex.vcproj
@@ -166,7 +166,7 @@
 			ConfigurationType="1"
 			InheritedPropertySheets=".\ffms2_include_dirs.vsprops"
 			CharacterSet="1"
-			WholeProgramOptimization="0"
+			WholeProgramOptimization="1"
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
@@ -186,14 +186,9 @@
 			<Tool
 				Name="VCCLCompilerTool"
 				Optimization="2"
-				InlineFunctionExpansion="2"
-				EnableIntrinsicFunctions="true"
-				FavorSizeOrSpeed="1"
 				OmitFramePointers="true"
 				PreprocessorDefinitions="_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS"
-				StringPooling="true"
 				RuntimeLibrary="0"
-				EnableFunctionLevelLinking="true"
 				WarningLevel="3"
 				DebugInformationFormat="3"
 				DisableSpecificWarnings="4995"
@@ -209,7 +204,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				GenerateDebugInformation="false"
+				GenerateDebugInformation="true"
 				OptimizeReferences="2"
 				EnableCOMDATFolding="2"
 				TargetMachine="1"
@@ -243,7 +238,7 @@
 			ConfigurationType="1"
 			InheritedPropertySheets=".\ffms2_include_dirs.vsprops"
 			CharacterSet="1"
-			WholeProgramOptimization="0"
+			WholeProgramOptimization="1"
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
@@ -264,14 +259,9 @@
 			<Tool
 				Name="VCCLCompilerTool"
 				Optimization="2"
-				InlineFunctionExpansion="2"
-				EnableIntrinsicFunctions="true"
-				FavorSizeOrSpeed="1"
 				OmitFramePointers="true"
 				PreprocessorDefinitions="_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS"
-				StringPooling="true"
 				RuntimeLibrary="0"
-				EnableFunctionLevelLinking="true"
 				WarningLevel="3"
 				DebugInformationFormat="3"
 				DisableSpecificWarnings="4995"
@@ -287,7 +277,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				GenerateDebugInformation="false"
+				GenerateDebugInformation="true"
 				OptimizeReferences="2"
 				EnableCOMDATFolding="2"
 				TargetMachine="17"
diff --git a/build-msvc/ffmsindex.vcxproj b/build-msvc/ffmsindex.vcxproj
index 9de0095..66b2f9f 100644
--- a/build-msvc/ffmsindex.vcxproj
+++ b/build-msvc/ffmsindex.vcxproj
@@ -26,7 +26,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization>false</WholeProgramOptimization>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
@@ -35,7 +35,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization>false</WholeProgramOptimization>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
@@ -94,6 +94,7 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+      <MultiProcessorCompilation>false</MultiProcessorCompilation>
     </ClCompile>
     <Link>
       <GenerateDebugInformation>true</GenerateDebugInformation>
@@ -103,23 +104,19 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
       <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
       <OmitFramePointers>true</OmitFramePointers>
-      <StringPooling>true</StringPooling>
+      <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
       <OptimizeReferences>true</OptimizeReferences>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <TargetMachine>MachineX86</TargetMachine>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
     </Link>
   </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
@@ -135,6 +132,7 @@
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+      <MultiProcessorCompilation>false</MultiProcessorCompilation>
     </ClCompile>
     <Link>
       <GenerateDebugInformation>true</GenerateDebugInformation>
@@ -147,20 +145,16 @@
     </Midl>
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
       <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
       <WarningLevel>Level3</WarningLevel>
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
       <DisableSpecificWarnings>4995;%(DisableSpecificWarnings)</DisableSpecificWarnings>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
       <OmitFramePointers>true</OmitFramePointers>
-      <StringPooling>true</StringPooling>
+      <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
       <OptimizeReferences>true</OptimizeReferences>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <TargetMachine>MachineX64</TargetMachine>
diff --git a/config.guess b/config.guess
index dc84c68..0e30d56 100755
--- a/config.guess
+++ b/config.guess
@@ -1,10 +1,9 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
-#   Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003 Free Software Foundation, Inc.
 
-timestamp='2009-11-20'
+timestamp='2003-07-02'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -18,25 +17,23 @@ timestamp='2009-11-20'
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
-# 02110-1301, USA.
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 #
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
 # the same distribution terms that you use for the rest of that program.
 
-
-# Originally written by Per Bothner.  Please send patches (context
-# diff format) to <config-patches at gnu.org> and include a ChangeLog
-# entry.
+# Originally written by Per Bothner <per at bothner.com>.
+# Please send patches to <config-patches at gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
 #
 # This script attempts to guess a canonical system name similar to
 # config.sub.  If it succeeds, it prints the system name on stdout, and
 # exits with 0.  Otherwise, it exits with 1.
 #
-# You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+# The plan is that this can be called by configure scripts if you
+# don't specify an explicit build system type.
 
 me=`echo "$0" | sed -e 's,.*/,,'`
 
@@ -56,8 +53,8 @@ version="\
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
-2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -69,11 +66,11 @@ Try \`$me --help' for more information."
 while test $# -gt 0 ; do
   case $1 in
     --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit ;;
+       echo "$timestamp" ; exit 0 ;;
     --version | -v )
-       echo "$version" ; exit ;;
+       echo "$version" ; exit 0 ;;
     --help | --h* | -h )
-       echo "$usage"; exit ;;
+       echo "$usage"; exit 0 ;;
     -- )     # Stop option processing
        shift; break ;;
     - )	# Use stdin as input.
@@ -107,7 +104,7 @@ set_cc_for_build='
 trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
 trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
 : ${TMPDIR=/tmp} ;
- { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
  { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
  { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
  { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
@@ -126,7 +123,7 @@ case $CC_FOR_BUILD,$HOST_CC,$CC in
 	;;
  ,,*)   CC_FOR_BUILD=$CC ;;
  ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
-esac ; set_cc_for_build= ;'
+esac ;'
 
 # This is needed to find uname on a Pyramid OSx when run in the BSD universe.
 # (ghazi at noc.rutgers.edu 1994-08-24)
@@ -161,7 +158,6 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	    arm*) machine=arm-unknown ;;
 	    sh3el) machine=shl-unknown ;;
 	    sh3eb) machine=sh-unknown ;;
-	    sh5el) machine=sh5le-unknown ;;
 	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
 	esac
 	# The Operating System including object format, if it has switched
@@ -170,7 +166,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
 		eval $set_cc_for_build
 		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
-			| grep -q __ELF__
+			| grep __ELF__ >/dev/null
 		then
 		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
 		    # Return netbsd for either.  FIX?
@@ -200,32 +196,50 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	# contains redundant information, the shorter form:
 	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
 	echo "${machine}-${os}${release}"
-	exit ;;
+	exit 0 ;;
+    amiga:OpenBSD:*:*)
+	echo m68k-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    arc:OpenBSD:*:*)
+	echo mipsel-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    hp300:OpenBSD:*:*)
+	echo m68k-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    mac68k:OpenBSD:*:*)
+	echo m68k-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    macppc:OpenBSD:*:*)
+	echo powerpc-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    mvme68k:OpenBSD:*:*)
+	echo m68k-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    mvme88k:OpenBSD:*:*)
+	echo m88k-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    mvmeppc:OpenBSD:*:*)
+	echo powerpc-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    pmax:OpenBSD:*:*)
+	echo mipsel-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    sgi:OpenBSD:*:*)
+	echo mipseb-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    sun3:OpenBSD:*:*)
+	echo m68k-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
+    wgrisc:OpenBSD:*:*)
+	echo mipsel-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
     *:OpenBSD:*:*)
-	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
-	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
-	exit ;;
-    *:ekkoBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
-	exit ;;
-    *:SolidBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
-	exit ;;
-    macppc:MirBSD:*:*)
-	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
-	exit ;;
-    *:MirBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
-	exit ;;
+	echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE}
+	exit 0 ;;
     alpha:OSF1:*:*)
-	case $UNAME_RELEASE in
-	*4.0)
+	if test $UNAME_RELEASE = "V4.0"; then
 		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
-		;;
-	*5.*)
-	        UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
-		;;
-	esac
+	fi
 	# According to Compaq, /usr/sbin/psrinfo has been available on
 	# OSF/1 and Tru64 systems produced since 1995.  I hope that
 	# covers most systems running today.  This code pipes the CPU
@@ -263,49 +277,42 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	    "EV7.9 (21364A)")
 		UNAME_MACHINE="alphaev79" ;;
 	esac
-	# A Pn.n version is a patched version.
 	# A Vn.n version is a released version.
 	# A Tn.n version is a released field test version.
 	# A Xn.n version is an unreleased experimental baselevel.
 	# 1.2 uses "1.2" for uname -r.
-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	exit ;;
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	exit 0 ;;
+    Alpha*:OpenVMS:*:*)
+	echo alpha-hp-vms
+	exit 0 ;;
     Alpha\ *:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# Should we change UNAME_MACHINE based on the output of uname instead
 	# of the specific Alpha model?
 	echo alpha-pc-interix
-	exit ;;
+	exit 0 ;;
     21064:Windows_NT:50:3)
 	echo alpha-dec-winnt3.5
-	exit ;;
+	exit 0 ;;
     Amiga*:UNIX_System_V:4.0:*)
 	echo m68k-unknown-sysv4
-	exit ;;
+	exit 0;;
     *:[Aa]miga[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-amigaos
-	exit ;;
+	exit 0 ;;
     *:[Mm]orph[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-morphos
-	exit ;;
+	exit 0 ;;
     *:OS/390:*:*)
 	echo i370-ibm-openedition
-	exit ;;
-    *:z/VM:*:*)
-	echo s390-ibm-zvmoe
-	exit ;;
-    *:OS400:*:*)
-        echo powerpc-ibm-os400
-	exit ;;
+	exit 0 ;;
     arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
 	echo arm-acorn-riscix${UNAME_RELEASE}
-	exit ;;
-    arm:riscos:*:*|arm:RISCOS:*:*)
-	echo arm-unknown-riscos
-	exit ;;
+	exit 0;;
     SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
 	echo hppa1.1-hitachi-hiuxmpp
-	exit ;;
+	exit 0;;
     Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
 	# akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
 	if test "`(/bin/universe) 2>/dev/null`" = att ; then
@@ -313,51 +320,32 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	else
 		echo pyramid-pyramid-bsd
 	fi
-	exit ;;
+	exit 0 ;;
     NILE*:*:*:dcosx)
 	echo pyramid-pyramid-svr4
-	exit ;;
+	exit 0 ;;
     DRS?6000:unix:4.0:6*)
 	echo sparc-icl-nx6
-	exit ;;
-    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+	exit 0 ;;
+    DRS?6000:UNIX_SV:4.2*:7*)
 	case `/usr/bin/uname -p` in
-	    sparc) echo sparc-icl-nx7; exit ;;
+	    sparc) echo sparc-icl-nx7 && exit 0 ;;
 	esac ;;
-    s390x:SunOS:*:*)
-	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
     sun4H:SunOS:5.*:*)
 	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
+	exit 0 ;;
     sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
 	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
-	echo i386-pc-auroraux${UNAME_RELEASE}
-	exit ;;
-    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
-	eval $set_cc_for_build
-	SUN_ARCH="i386"
-	# If there is a compiler, see if it is configured for 64-bit objects.
-	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
-	# This test works for both compilers.
-	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
-		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		grep IS_64BIT_ARCH >/dev/null
-	    then
-		SUN_ARCH="x86_64"
-	    fi
-	fi
-	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
+	exit 0 ;;
+    i86pc:SunOS:5.*:*)
+	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit 0 ;;
     sun4*:SunOS:6*:*)
 	# According to config.sub, this is the proper way to canonicalize
 	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
 	# it's likely to be more like Solaris than SunOS4.
 	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
+	exit 0 ;;
     sun4*:SunOS:*:*)
 	case "`/usr/bin/arch -k`" in
 	    Series*|S4*)
@@ -366,10 +354,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	esac
 	# Japanese Language versions have a version number like `4.1.3-JL'.
 	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
-	exit ;;
+	exit 0 ;;
     sun3*:SunOS:*:*)
 	echo m68k-sun-sunos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     sun*:*:4.2BSD:*)
 	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
 	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
@@ -381,10 +369,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 		echo sparc-sun-sunos${UNAME_RELEASE}
 		;;
 	esac
-	exit ;;
+	exit 0 ;;
     aushp:SunOS:*:*)
 	echo sparc-auspex-sunos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     # The situation for MiNT is a little confusing.  The machine name
     # can be virtually everything (everything which is not
     # "atarist" or "atariste" at least should have a processor
@@ -395,40 +383,37 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
     # be no problem.
     atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
         echo m68k-atari-mint${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
 	echo m68k-atari-mint${UNAME_RELEASE}
-        exit ;;
+        exit 0 ;;
     *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
         echo m68k-atari-mint${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
         echo m68k-milan-mint${UNAME_RELEASE}
-        exit ;;
+        exit 0 ;;
     hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
         echo m68k-hades-mint${UNAME_RELEASE}
-        exit ;;
+        exit 0 ;;
     *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
         echo m68k-unknown-mint${UNAME_RELEASE}
-        exit ;;
-    m68k:machten:*:*)
-	echo m68k-apple-machten${UNAME_RELEASE}
-	exit ;;
+        exit 0 ;;
     powerpc:machten:*:*)
 	echo powerpc-apple-machten${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     RISC*:Mach:*:*)
 	echo mips-dec-mach_bsd4.3
-	exit ;;
+	exit 0 ;;
     RISC*:ULTRIX:*:*)
 	echo mips-dec-ultrix${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     VAX*:ULTRIX*:*:*)
 	echo vax-dec-ultrix${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     2020:CLIX:*:* | 2430:CLIX:*:*)
 	echo clipper-intergraph-clix${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     mips:*:*:UMIPS | mips:*:*:RISCos)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -452,33 +437,32 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	  exit (-1);
 	}
 EOF
-	$CC_FOR_BUILD -o $dummy $dummy.c &&
-	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
-	  SYSTEM_NAME=`$dummy $dummyarg` &&
-	    { echo "$SYSTEM_NAME"; exit; }
+	$CC_FOR_BUILD -o $dummy $dummy.c \
+	  && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
+	  && exit 0
 	echo mips-mips-riscos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     Motorola:PowerMAX_OS:*:*)
 	echo powerpc-motorola-powermax
-	exit ;;
+	exit 0 ;;
     Motorola:*:4.3:PL8-*)
 	echo powerpc-harris-powermax
-	exit ;;
+	exit 0 ;;
     Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
 	echo powerpc-harris-powermax
-	exit ;;
+	exit 0 ;;
     Night_Hawk:Power_UNIX:*:*)
 	echo powerpc-harris-powerunix
-	exit ;;
+	exit 0 ;;
     m88k:CX/UX:7*:*)
 	echo m88k-harris-cxux7
-	exit ;;
+	exit 0 ;;
     m88k:*:4*:R4*)
 	echo m88k-motorola-sysv4
-	exit ;;
+	exit 0 ;;
     m88k:*:3*:R3*)
 	echo m88k-motorola-sysv3
-	exit ;;
+	exit 0 ;;
     AViiON:dgux:*:*)
         # DG/UX returns AViiON for all architectures
         UNAME_PROCESSOR=`/usr/bin/uname -p`
@@ -494,29 +478,29 @@ EOF
 	else
 	    echo i586-dg-dgux${UNAME_RELEASE}
 	fi
- 	exit ;;
+ 	exit 0 ;;
     M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
 	echo m88k-dolphin-sysv3
-	exit ;;
+	exit 0 ;;
     M88*:*:R3*:*)
 	# Delta 88k system running SVR3
 	echo m88k-motorola-sysv3
-	exit ;;
+	exit 0 ;;
     XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
 	echo m88k-tektronix-sysv3
-	exit ;;
+	exit 0 ;;
     Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
 	echo m68k-tektronix-bsd
-	exit ;;
+	exit 0 ;;
     *:IRIX*:*:*)
 	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
-	exit ;;
+	exit 0 ;;
     ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
-	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
-	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
+	echo romp-ibm-aix      # uname -m gives an 8 hex-code CPU id
+	exit 0 ;;              # Note that: echo "'`uname -s`'" gives 'AIX '
     i*86:AIX:*:*)
 	echo i386-ibm-aix
-	exit ;;
+	exit 0 ;;
     ia64:AIX:*:*)
 	if [ -x /usr/bin/oslevel ] ; then
 		IBM_REV=`/usr/bin/oslevel`
@@ -524,7 +508,7 @@ EOF
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
 	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
-	exit ;;
+	exit 0 ;;
     *:AIX:2:3)
 	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
 		eval $set_cc_for_build
@@ -539,19 +523,15 @@ EOF
 			exit(0);
 			}
 EOF
-		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
-		then
-			echo "$SYSTEM_NAME"
-		else
-			echo rs6000-ibm-aix3.2.5
-		fi
+		$CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
+		echo rs6000-ibm-aix3.2.5
 	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
 		echo rs6000-ibm-aix3.2.4
 	else
 		echo rs6000-ibm-aix3.2
 	fi
-	exit ;;
-    *:AIX:*:[456])
+	exit 0 ;;
+    *:AIX:*:[45])
 	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
 	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
 		IBM_ARCH=rs6000
@@ -564,28 +544,28 @@ EOF
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
 	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
-	exit ;;
+	exit 0 ;;
     *:AIX:*:*)
 	echo rs6000-ibm-aix
-	exit ;;
+	exit 0 ;;
     ibmrt:4.4BSD:*|romp-ibm:BSD:*)
 	echo romp-ibm-bsd4.4
-	exit ;;
+	exit 0 ;;
     ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
 	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
-	exit ;;                             # report: romp-ibm BSD 4.3
+	exit 0 ;;                           # report: romp-ibm BSD 4.3
     *:BOSX:*:*)
 	echo rs6000-bull-bosx
-	exit ;;
+	exit 0 ;;
     DPX/2?00:B.O.S.:*:*)
 	echo m68k-bull-sysv3
-	exit ;;
+	exit 0 ;;
     9000/[34]??:4.3bsd:1.*:*)
 	echo m68k-hp-bsd
-	exit ;;
+	exit 0 ;;
     hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
 	echo m68k-hp-bsd4.4
-	exit ;;
+	exit 0 ;;
     9000/[34678]??:HP-UX:*:*)
 	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	case "${UNAME_MACHINE}" in
@@ -647,19 +627,9 @@ EOF
 	esac
 	if [ ${HP_ARCH} = "hppa2.0w" ]
 	then
-	    eval $set_cc_for_build
-
-	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
-	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
-	    # generating 64-bit code.  GNU and HP use different nomenclature:
-	    #
-	    # $ CC_FOR_BUILD=cc ./config.guess
-	    # => hppa2.0w-hp-hpux11.23
-	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
-	    # => hppa64-hp-hpux11.23
-
-	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
-		grep -q __LP64__
+	    # avoid double evaluation of $set_cc_for_build
+	    test -n "$CC_FOR_BUILD" || eval $set_cc_for_build
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null
 	    then
 		HP_ARCH="hppa2.0w"
 	    else
@@ -667,11 +637,11 @@ EOF
 	    fi
 	fi
 	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
-	exit ;;
+	exit 0 ;;
     ia64:HP-UX:*:*)
 	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	echo ia64-hp-hpux${HPUX_REV}
-	exit ;;
+	exit 0 ;;
     3050*:HI-UX:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -699,248 +669,211 @@ EOF
 	  exit (0);
 	}
 EOF
-	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
-		{ echo "$SYSTEM_NAME"; exit; }
+	$CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
 	echo unknown-hitachi-hiuxwe2
-	exit ;;
+	exit 0 ;;
     9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
 	echo hppa1.1-hp-bsd
-	exit ;;
+	exit 0 ;;
     9000/8??:4.3bsd:*:*)
 	echo hppa1.0-hp-bsd
-	exit ;;
+	exit 0 ;;
     *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
 	echo hppa1.0-hp-mpeix
-	exit ;;
+	exit 0 ;;
     hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
 	echo hppa1.1-hp-osf
-	exit ;;
+	exit 0 ;;
     hp8??:OSF1:*:*)
 	echo hppa1.0-hp-osf
-	exit ;;
+	exit 0 ;;
     i*86:OSF1:*:*)
 	if [ -x /usr/sbin/sysversion ] ; then
 	    echo ${UNAME_MACHINE}-unknown-osf1mk
 	else
 	    echo ${UNAME_MACHINE}-unknown-osf1
 	fi
-	exit ;;
+	exit 0 ;;
     parisc*:Lites*:*:*)
 	echo hppa1.1-hp-lites
-	exit ;;
+	exit 0 ;;
     C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
 	echo c1-convex-bsd
-        exit ;;
+        exit 0 ;;
     C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
 	if getsysinfo -f scalar_acc
 	then echo c32-convex-bsd
 	else echo c2-convex-bsd
 	fi
-        exit ;;
+        exit 0 ;;
     C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
 	echo c34-convex-bsd
-        exit ;;
+        exit 0 ;;
     C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
 	echo c38-convex-bsd
-        exit ;;
+        exit 0 ;;
     C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
 	echo c4-convex-bsd
-        exit ;;
+        exit 0 ;;
     CRAY*Y-MP:*:*:*)
 	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
+	exit 0 ;;
     CRAY*[A-Z]90:*:*:*)
 	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
 	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
 	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
 	      -e 's/\.[^.]*$/.X/'
-	exit ;;
+	exit 0 ;;
     CRAY*TS:*:*:*)
 	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
+	exit 0 ;;
     CRAY*T3E:*:*:*)
 	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
+	exit 0 ;;
     CRAY*SV1:*:*:*)
 	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
+	exit 0 ;;
     *:UNICOS/mp:*:*)
-	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
+	echo nv1-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' 
+	exit 0 ;;
     F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
 	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
         FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
         FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
         echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
-        exit ;;
-    5000:UNIX_System_V:4.*:*)
-        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
-        FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
-        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
-	exit ;;
+        exit 0 ;;
     i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
 	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     sparc*:BSD/OS:*:*)
 	echo sparc-unknown-bsdi${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:BSD/OS:*:*)
 	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
-	exit ;;
-    *:FreeBSD:*:*)
-	case ${UNAME_MACHINE} in
-	    pc98)
-		echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
-	    amd64)
-		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
-	    *)
-		echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
-	esac
-	exit ;;
+	exit 0 ;;
+    *:FreeBSD:*:*|*:GNU/FreeBSD:*:*)
+	# Determine whether the default compiler uses glibc.
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <features.h>
+	#if __GLIBC__ >= 2
+	LIBC=gnu
+	#else
+	LIBC=
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
+	# GNU/FreeBSD systems have a "k" prefix to indicate we are using
+	# FreeBSD's kernel, but not the complete OS.
+	case ${LIBC} in gnu) kernel_only='k' ;; esac
+	echo ${UNAME_MACHINE}-unknown-${kernel_only}freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`${LIBC:+-$LIBC}
+	exit 0 ;;
     i*:CYGWIN*:*)
 	echo ${UNAME_MACHINE}-pc-cygwin
-	exit ;;
-    *:MINGW*:*)
+	exit 0 ;;
+    i*:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
-	exit ;;
-    i*:windows32*:*)
-    	# uname -m includes "-pc" on this system.
-    	echo ${UNAME_MACHINE}-mingw32
-	exit ;;
+	exit 0 ;;
     i*:PW*:*)
 	echo ${UNAME_MACHINE}-pc-pw32
-	exit ;;
-    *:Interix*:*)
-    	case ${UNAME_MACHINE} in
-	    x86)
-		echo i586-pc-interix${UNAME_RELEASE}
-		exit ;;
-	    authenticamd | genuineintel | EM64T)
-		echo x86_64-unknown-interix${UNAME_RELEASE}
-		exit ;;
-	    IA64)
-		echo ia64-unknown-interix${UNAME_RELEASE}
-		exit ;;
-	esac ;;
+	exit 0 ;;
+    x86:Interix*:[34]*)
+	echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//'
+	exit 0 ;;
     [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
 	echo i${UNAME_MACHINE}-pc-mks
-	exit ;;
-    8664:Windows_NT:*)
-	echo x86_64-pc-mks
-	exit ;;
+	exit 0 ;;
     i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
 	# UNAME_MACHINE based on the output of uname instead of i386?
 	echo i586-pc-interix
-	exit ;;
+	exit 0 ;;
     i*:UWIN*:*)
 	echo ${UNAME_MACHINE}-pc-uwin
-	exit ;;
-    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
-	echo x86_64-unknown-cygwin
-	exit ;;
+	exit 0 ;;
     p*:CYGWIN*:*)
 	echo powerpcle-unknown-cygwin
-	exit ;;
+	exit 0 ;;
     prep*:SunOS:5.*:*)
 	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
+	exit 0 ;;
     *:GNU:*:*)
-	# the GNU system
 	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
-	exit ;;
-    *:GNU/*:*:*)
-	# other systems with GNU libc and userland
-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
-	exit ;;
+	exit 0 ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
-	exit ;;
-    alpha:Linux:*:*)
-	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
-	  EV5)   UNAME_MACHINE=alphaev5 ;;
-	  EV56)  UNAME_MACHINE=alphaev56 ;;
-	  PCA56) UNAME_MACHINE=alphapca56 ;;
-	  PCA57) UNAME_MACHINE=alphapca56 ;;
-	  EV6)   UNAME_MACHINE=alphaev6 ;;
-	  EV67)  UNAME_MACHINE=alphaev67 ;;
-	  EV68*) UNAME_MACHINE=alphaev68 ;;
-        esac
-	objdump --private-headers /bin/sh | grep -q ld.so.1
-	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
-	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
-	exit ;;
+	exit 0 ;;
     arm*:Linux:*:*)
-	eval $set_cc_for_build
-	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
-	    | grep -q __ARM_EABI__
-	then
-	    echo ${UNAME_MACHINE}-unknown-linux-gnu
-	else
-	    echo ${UNAME_MACHINE}-unknown-linux-gnueabi
-	fi
-	exit ;;
-    avr32*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
+	exit 0 ;;
     cris:Linux:*:*)
 	echo cris-axis-linux-gnu
-	exit ;;
-    crisv32:Linux:*:*)
-	echo crisv32-axis-linux-gnu
-	exit ;;
-    frv:Linux:*:*)
-    	echo frv-unknown-linux-gnu
-	exit ;;
-    i*86:Linux:*:*)
-	LIBC=gnu
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#ifdef __dietlibc__
-	LIBC=dietlibc
-	#endif
-EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
-	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
-	exit ;;
+	exit 0 ;;
     ia64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
-    m32r*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
+	exit 0 ;;
     m68*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
-    mips:Linux:*:* | mips64:Linux:*:*)
+	exit 0 ;;
+    mips:Linux:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
 	#undef CPU
-	#undef ${UNAME_MACHINE}
-	#undef ${UNAME_MACHINE}el
+	#undef mips
+	#undef mipsel
 	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
-	CPU=${UNAME_MACHINE}el
+	CPU=mipsel
 	#else
 	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
-	CPU=${UNAME_MACHINE}
+	CPU=mips
 	#else
 	CPU=
 	#endif
 	#endif
 EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
-	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
+	test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
 	;;
-    or32:Linux:*:*)
-	echo or32-unknown-linux-gnu
-	exit ;;
-    padre:Linux:*:*)
-	echo sparc-unknown-linux-gnu
-	exit ;;
-    parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-gnu
-	exit ;;
+    mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef mips64
+	#undef mips64el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=mips64el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=mips64
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
+	test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
+	;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-gnu
+	exit 0 ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-gnu
+	exit 0 ;;
+    alpha:Linux:*:*)
+	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+	  EV5)   UNAME_MACHINE=alphaev5 ;;
+	  EV56)  UNAME_MACHINE=alphaev56 ;;
+	  PCA56) UNAME_MACHINE=alphapca56 ;;
+	  PCA57) UNAME_MACHINE=alphapca56 ;;
+	  EV6)   UNAME_MACHINE=alphaev6 ;;
+	  EV67)  UNAME_MACHINE=alphaev67 ;;
+	  EV68*) UNAME_MACHINE=alphaev68 ;;
+        esac
+	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	exit 0 ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
@@ -948,40 +881,84 @@ EOF
 	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
 	  *)    echo hppa-unknown-linux-gnu ;;
 	esac
-	exit ;;
-    ppc64:Linux:*:*)
-	echo powerpc64-unknown-linux-gnu
-	exit ;;
-    ppc:Linux:*:*)
-	echo powerpc-unknown-linux-gnu
-	exit ;;
+	exit 0 ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-gnu
+	exit 0 ;;
     s390:Linux:*:* | s390x:Linux:*:*)
 	echo ${UNAME_MACHINE}-ibm-linux
-	exit ;;
+	exit 0 ;;
     sh64*:Linux:*:*)
     	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
+	exit 0 ;;
     sh*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
+	exit 0 ;;
     sparc:Linux:*:* | sparc64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
-    vax:Linux:*:*)
-	echo ${UNAME_MACHINE}-dec-linux-gnu
-	exit ;;
+	exit 0 ;;
     x86_64:Linux:*:*)
 	echo x86_64-unknown-linux-gnu
-	exit ;;
-    xtensa*:Linux:*:*)
-    	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit ;;
+	exit 0 ;;
+    i*86:Linux:*:*)
+	# The BFD linker knows what the default object file format is, so
+	# first see if it will tell us. cd to the root directory to prevent
+	# problems with other programs or directories called `ld' in the path.
+	# Set LC_ALL=C to ensure ld outputs messages in English.
+	ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
+			 | sed -ne '/supported targets:/!d
+				    s/[ 	][ 	]*/ /g
+				    s/.*supported targets: *//
+				    s/ .*//
+				    p'`
+        case "$ld_supported_targets" in
+	  elf32-i386)
+		TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
+		;;
+	  a.out-i386-linux)
+		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
+		exit 0 ;;
+	  coff-i386)
+		echo "${UNAME_MACHINE}-pc-linux-gnucoff"
+		exit 0 ;;
+	  "")
+		# Either a pre-BFD a.out linker (linux-gnuoldld) or
+		# one that does not give us useful --help.
+		echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
+		exit 0 ;;
+	esac
+	# Determine whether the default compiler is a.out or elf
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <features.h>
+	#ifdef __ELF__
+	# ifdef __GLIBC__
+	#  if __GLIBC__ >= 2
+	LIBC=gnu
+	#  else
+	LIBC=gnulibc1
+	#  endif
+	# else
+	LIBC=gnulibc1
+	# endif
+	#else
+	#ifdef __INTEL_COMPILER
+	LIBC=gnu
+	#else
+	LIBC=gnuaout
+	#endif
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
+	test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0
+	test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
+	;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
 	# earlier versions are messed up and put the nodename in both
 	# sysname and nodename.
 	echo i386-sequent-sysv4
-	exit ;;
+	exit 0 ;;
     i*86:UNIX_SV:4.2MP:2.*)
         # Unixware is an offshoot of SVR4, but it has its own version
         # number series starting with 2...
@@ -989,27 +966,24 @@ EOF
 	# I just have to hope.  -- rms.
         # Use sysv4.2uw... so that sysv4* matches it.
 	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
-	exit ;;
+	exit 0 ;;
     i*86:OS/2:*:*)
 	# If we were able to find `uname', then EMX Unix compatibility
 	# is probably installed.
 	echo ${UNAME_MACHINE}-pc-os2-emx
-	exit ;;
+	exit 0 ;;
     i*86:XTS-300:*:STOP)
 	echo ${UNAME_MACHINE}-unknown-stop
-	exit ;;
+	exit 0 ;;
     i*86:atheos:*:*)
 	echo ${UNAME_MACHINE}-unknown-atheos
-	exit ;;
-    i*86:syllable:*:*)
-	echo ${UNAME_MACHINE}-pc-syllable
-	exit ;;
-    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+	exit 0 ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
 	echo i386-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     i*86:*DOS:*:*)
 	echo ${UNAME_MACHINE}-pc-msdosdjgpp
-	exit ;;
+	exit 0 ;;
     i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
 	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
 	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
@@ -1017,16 +991,15 @@ EOF
 	else
 		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
 	fi
-	exit ;;
-    i*86:*:5:[678]*)
-    	# UnixWare 7.x, OpenUNIX and OpenServer 6.
+	exit 0 ;;
+    i*86:*:5:[78]*)
 	case `/bin/uname -X | grep "^Machine"` in
 	    *486*)	     UNAME_MACHINE=i486 ;;
 	    *Pentium)	     UNAME_MACHINE=i586 ;;
 	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
 	esac
 	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
-	exit ;;
+	exit 0 ;;
     i*86:*:3.2:*)
 	if test -f /usr/options/cb.name; then
 		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
@@ -1044,86 +1017,73 @@ EOF
 	else
 		echo ${UNAME_MACHINE}-pc-sysv32
 	fi
-	exit ;;
+	exit 0 ;;
     pc:*:*:*)
 	# Left here for compatibility:
         # uname -m prints for DJGPP always 'pc', but it prints nothing about
-        # the processor, so we play safe by assuming i586.
-	# Note: whatever this is, it MUST be the same as what config.sub
-	# prints for the "djgpp" host, or else GDB configury will decide that
-	# this is a cross-build.
-	echo i586-pc-msdosdjgpp
-        exit ;;
+        # the processor, so we play safe by assuming i386.
+	echo i386-pc-msdosdjgpp
+        exit 0 ;;
     Intel:Mach:3*:*)
 	echo i386-pc-mach3
-	exit ;;
+	exit 0 ;;
     paragon:*:*:*)
 	echo i860-intel-osf1
-	exit ;;
+	exit 0 ;;
     i860:*:4.*:*) # i860-SVR4
 	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
 	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
 	else # Add other i860-SVR4 vendors below as they are discovered.
 	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
 	fi
-	exit ;;
+	exit 0 ;;
     mini*:CTIX:SYS*5:*)
 	# "miniframe"
 	echo m68010-convergent-sysv
-	exit ;;
+	exit 0 ;;
     mc68k:UNIX:SYSTEM5:3.51m)
 	echo m68k-convergent-sysv
-	exit ;;
+	exit 0 ;;
     M680?0:D-NIX:5.3:*)
 	echo m68k-diab-dnix
-	exit ;;
-    M68*:*:R3V[5678]*:*)
-	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
-    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+	exit 0 ;;
+    M68*:*:R3V[567]*:*)
+	test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
+    3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0)
 	OS_REL=''
 	test -r /etc/.relid \
 	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
 	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	  && echo i486-ncr-sysv4.3${OS_REL} && exit 0
 	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
-	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+	  && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
     3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
         /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-          && { echo i486-ncr-sysv4; exit; } ;;
-    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
-	OS_REL='.3'
-	test -r /etc/.relid \
-	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
-	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
-	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
-	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
-	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+          && echo i486-ncr-sysv4 && exit 0 ;;
     m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
 	echo m68k-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     mc68030:UNIX_System_V:4.*:*)
 	echo m68k-atari-sysv4
-	exit ;;
+	exit 0 ;;
     TSUNAMI:LynxOS:2.*:*)
 	echo sparc-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     rs6000:LynxOS:2.*:*)
 	echo rs6000-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
-    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+	exit 0 ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
 	echo powerpc-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     SM[BE]S:UNIX_SV:*:*)
 	echo mips-dde-sysv${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     RM*:ReliantUNIX-*:*:*)
 	echo mips-sni-sysv4
-	exit ;;
+	exit 0 ;;
     RM*:SINIX-*:*:*)
 	echo mips-sni-sysv4
-	exit ;;
+	exit 0 ;;
     *:SINIX-*:*:*)
 	if uname -p 2>/dev/null >/dev/null ; then
 		UNAME_MACHINE=`(uname -p) 2>/dev/null`
@@ -1131,94 +1091,68 @@ EOF
 	else
 		echo ns32k-sni-sysv
 	fi
-	exit ;;
+	exit 0 ;;
     PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
                       # says <Richard.M.Bartel at ccMail.Census.GOV>
         echo i586-unisys-sysv4
-        exit ;;
+        exit 0 ;;
     *:UNIX_System_V:4*:FTX*)
 	# From Gerald Hewes <hewes at openmarket.com>.
 	# How about differentiating between stratus architectures? -djm
 	echo hppa1.1-stratus-sysv4
-	exit ;;
+	exit 0 ;;
     *:*:*:FTX*)
 	# From seanf at swdc.stratus.com.
 	echo i860-stratus-sysv4
-	exit ;;
-    i*86:VOS:*:*)
-	# From Paul.Green at stratus.com.
-	echo ${UNAME_MACHINE}-stratus-vos
-	exit ;;
+	exit 0 ;;
     *:VOS:*:*)
 	# From Paul.Green at stratus.com.
 	echo hppa1.1-stratus-vos
-	exit ;;
+	exit 0 ;;
     mc68*:A/UX:*:*)
 	echo m68k-apple-aux${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     news*:NEWS-OS:6*:*)
 	echo mips-sony-newsos6
-	exit ;;
+	exit 0 ;;
     R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
 	if [ -d /usr/nec ]; then
 	        echo mips-nec-sysv${UNAME_RELEASE}
 	else
 	        echo mips-unknown-sysv${UNAME_RELEASE}
 	fi
-        exit ;;
+        exit 0 ;;
     BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
 	echo powerpc-be-beos
-	exit ;;
+	exit 0 ;;
     BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
 	echo powerpc-apple-beos
-	exit ;;
+	exit 0 ;;
     BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
 	echo i586-pc-beos
-	exit ;;
-    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
-	echo i586-pc-haiku
-	exit ;;
+	exit 0 ;;
     SX-4:SUPER-UX:*:*)
 	echo sx4-nec-superux${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     SX-5:SUPER-UX:*:*)
 	echo sx5-nec-superux${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     SX-6:SUPER-UX:*:*)
 	echo sx6-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-7:SUPER-UX:*:*)
-	echo sx7-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-8:SUPER-UX:*:*)
-	echo sx8-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-8R:SUPER-UX:*:*)
-	echo sx8r-nec-superux${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     Power*:Rhapsody:*:*)
 	echo powerpc-apple-rhapsody${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:Rhapsody:*:*)
 	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:Darwin:*:*)
-	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
-	case $UNAME_PROCESSOR in
-	    i386)
-		eval $set_cc_for_build
-		if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-		      (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		      grep IS_64BIT_ARCH >/dev/null
-		  then
-		      UNAME_PROCESSOR="x86_64"
-		  fi
-		fi ;;
-	    unknown) UNAME_PROCESSOR=powerpc ;;
+	case `uname -p` in
+	    *86) UNAME_PROCESSOR=i686 ;;
+	    powerpc) UNAME_PROCESSOR=powerpc ;;
 	esac
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
 	UNAME_PROCESSOR=`uname -p`
 	if test "$UNAME_PROCESSOR" = "x86"; then
@@ -1226,25 +1160,22 @@ EOF
 		UNAME_MACHINE=pc
 	fi
 	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:QNX:*:4*)
 	echo i386-pc-qnx
-	exit ;;
-    NSE-?:NONSTOP_KERNEL:*:*)
-	echo nse-tandem-nsk${UNAME_RELEASE}
-	exit ;;
-    NSR-?:NONSTOP_KERNEL:*:*)
+	exit 0 ;;
+    NSR-[DGKLNPTVW]:NONSTOP_KERNEL:*:*)
 	echo nsr-tandem-nsk${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:NonStop-UX:*:*)
 	echo mips-compaq-nonstopux
-	exit ;;
+	exit 0 ;;
     BS2000:POSIX*:*:*)
 	echo bs2000-siemens-sysv
-	exit ;;
+	exit 0 ;;
     DS/*:UNIX_System_V:*:*)
 	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
-	exit ;;
+	exit 0 ;;
     *:Plan9:*:*)
 	# "uname -m" is not consistent, so use $cputype instead. 386
 	# is converted to i386 for consistency with other x86
@@ -1255,50 +1186,28 @@ EOF
 	    UNAME_MACHINE="$cputype"
 	fi
 	echo ${UNAME_MACHINE}-unknown-plan9
-	exit ;;
+	exit 0 ;;
     *:TOPS-10:*:*)
 	echo pdp10-unknown-tops10
-	exit ;;
+	exit 0 ;;
     *:TENEX:*:*)
 	echo pdp10-unknown-tenex
-	exit ;;
+	exit 0 ;;
     KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
 	echo pdp10-dec-tops20
-	exit ;;
+	exit 0 ;;
     XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
 	echo pdp10-xkl-tops20
-	exit ;;
+	exit 0 ;;
     *:TOPS-20:*:*)
 	echo pdp10-unknown-tops20
-	exit ;;
+	exit 0 ;;
     *:ITS:*:*)
 	echo pdp10-unknown-its
-	exit ;;
+	exit 0 ;;
     SEI:*:*:SEIUX)
         echo mips-sei-seiux${UNAME_RELEASE}
-	exit ;;
-    *:DragonFly:*:*)
-	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
-	exit ;;
-    *:*VMS:*:*)
-    	UNAME_MACHINE=`(uname -p) 2>/dev/null`
-	case "${UNAME_MACHINE}" in
-	    A*) echo alpha-dec-vms ; exit ;;
-	    I*) echo ia64-dec-vms ; exit ;;
-	    V*) echo vax-dec-vms ; exit ;;
-	esac ;;
-    *:XENIX:*:SysV)
-	echo i386-pc-xenix
-	exit ;;
-    i*86:skyos:*:*)
-	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
-	exit ;;
-    i*86:rdos:*:*)
-	echo ${UNAME_MACHINE}-pc-rdos
-	exit ;;
-    i*86:AROS:*:*)
-	echo ${UNAME_MACHINE}-pc-aros
-	exit ;;
+	exit 0 ;;
 esac
 
 #echo '(No uname command or uname output not recognized.)' 1>&2
@@ -1330,7 +1239,7 @@ main ()
 #endif
 
 #if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix\n"); exit (0);
+  printf ("arm-acorn-riscix"); exit (0);
 #endif
 
 #if defined (hp300) && !defined (hpux)
@@ -1419,12 +1328,11 @@ main ()
 }
 EOF
 
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
-	{ echo "$SYSTEM_NAME"; exit; }
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0
 
 # Apollos put the system type in the environment.
 
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
 
 # Convex versions that predate uname can use getsysinfo(1)
 
@@ -1433,22 +1341,22 @@ then
     case `getsysinfo -f cpu_type` in
     c1*)
 	echo c1-convex-bsd
-	exit ;;
+	exit 0 ;;
     c2*)
 	if getsysinfo -f scalar_acc
 	then echo c32-convex-bsd
 	else echo c2-convex-bsd
 	fi
-	exit ;;
+	exit 0 ;;
     c34*)
 	echo c34-convex-bsd
-	exit ;;
+	exit 0 ;;
     c38*)
 	echo c38-convex-bsd
-	exit ;;
+	exit 0 ;;
     c4*)
 	echo c4-convex-bsd
-	exit ;;
+	exit 0 ;;
     esac
 fi
 
@@ -1459,9 +1367,7 @@ This script, last modified $timestamp, has failed to recognize
 the operating system you are using. It is advised that you
 download the most up to date version of the config scripts from
 
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
-and
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+    ftp://ftp.gnu.org/pub/gnu/config/
 
 If the version you run ($0) is already up to date, please
 send the following data and any information you think might be
diff --git a/config.sub b/config.sub
index 2a55a50..9d7f733 100755
--- a/config.sub
+++ b/config.sub
@@ -1,10 +1,9 @@
 #! /bin/sh
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
-#   Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003 Free Software Foundation, Inc.
 
-timestamp='2009-11-20'
+timestamp='2003-07-04'
 
 # This file is (in principle) common to ALL GNU software.
 # The presence of a machine in this file suggests that SOME GNU software
@@ -22,26 +21,22 @@ timestamp='2009-11-20'
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
-# 02110-1301, USA.
-#
+# Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
 # the same distribution terms that you use for the rest of that program.
 
-
 # Please send patches to <config-patches at gnu.org>.  Submit a context
-# diff and a properly formatted GNU ChangeLog entry.
+# diff and a properly formatted ChangeLog entry.
 #
 # Configuration subroutine to validate and canonicalize a configuration type.
 # Supply the specified configuration type as an argument.
 # If it is invalid, we print an error message on stderr and exit with code 1.
 # Otherwise, we print the canonical config type on stdout and succeed.
 
-# You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
-
 # This file is supposed to be the same for all GNU packages
 # and recognize all the CPU types, system types and aliases
 # that are meaningful with *any* GNU software.
@@ -75,8 +70,8 @@ Report bugs and patches to <config-patches at gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
-2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -88,11 +83,11 @@ Try \`$me --help' for more information."
 while test $# -gt 0 ; do
   case $1 in
     --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit ;;
+       echo "$timestamp" ; exit 0 ;;
     --version | -v )
-       echo "$version" ; exit ;;
+       echo "$version" ; exit 0 ;;
     --help | --h* | -h )
-       echo "$usage"; exit ;;
+       echo "$usage"; exit 0 ;;
     -- )     # Stop option processing
        shift; break ;;
     - )	# Use stdin as input.
@@ -104,7 +99,7 @@ while test $# -gt 0 ; do
     *local*)
        # First pass through any local machine types.
        echo $1
-       exit ;;
+       exit 0;;
 
     * )
        break ;;
@@ -123,10 +118,7 @@ esac
 # Here we must recognize all the valid KERNEL-OS combinations.
 maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
 case $maybe_os in
-  nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
-  uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
-  kopensolaris*-gnu* | \
-  storm-chaos* | os2-emx* | rtmk-nova*)
+  nto-qnx* | linux-gnu* | kfreebsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
     ;;
@@ -152,13 +144,10 @@ case $os in
 	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
 	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
 	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-	-apple | -axis | -knuth | -cray | -microblaze)
+	-apple | -axis)
 		os=
 		basic_machine=$1
 		;;
-        -bluegene*)
-	        os=-cnk
-		;;
 	-sim | -cisco | -oki | -wec | -winbond)
 		os=
 		basic_machine=$1
@@ -180,10 +169,6 @@ case $os in
 	-hiux*)
 		os=-hiuxwe2
 		;;
-	-sco6)
-		os=-sco5v6
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
 	-sco5)
 		os=-sco3.2v5
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
@@ -200,10 +185,6 @@ case $os in
 		# Don't forget version if it is 3.2v4 or newer.
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
 		;;
-	-sco5v6*)
-		# Don't forget version if it is 3.2v4 or newer.
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
 	-sco*)
 		os=-sco3.2v2
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
@@ -247,71 +228,53 @@ case $basic_machine in
 	| a29k \
 	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
 	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
-	| am33_2.0 \
-	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
-	| bfin \
+	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
 	| c4x | clipper \
 	| d10v | d30v | dlx | dsp16xx \
-	| fido | fr30 | frv \
+	| fr30 | frv \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
 	| i370 | i860 | i960 | ia64 \
-	| ip2k | iq2000 \
-	| lm32 \
-	| m32c | m32r | m32rle | m68000 | m68k | m88k \
-	| maxq | mb | microblaze | mcore | mep | metag \
+	| ip2k \
+	| m32r | m68000 | m68k | m88k | mcore \
 	| mips | mipsbe | mipseb | mipsel | mipsle \
 	| mips16 \
 	| mips64 | mips64el \
-	| mips64octeon | mips64octeonel \
-	| mips64orion | mips64orionel \
-	| mips64r5900 | mips64r5900el \
 	| mips64vr | mips64vrel \
+	| mips64orion | mips64orionel \
 	| mips64vr4100 | mips64vr4100el \
 	| mips64vr4300 | mips64vr4300el \
 	| mips64vr5000 | mips64vr5000el \
-	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
 	| mipsisa64 | mipsisa64el \
-	| mipsisa64r2 | mipsisa64r2el \
 	| mipsisa64sb1 | mipsisa64sb1el \
 	| mipsisa64sr71k | mipsisa64sr71kel \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
-	| moxie \
-	| mt \
 	| msp430 \
-	| nios | nios2 \
 	| ns16k | ns32k \
-	| or32 \
+	| openrisc | or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
 	| pyramid \
-	| rx \
-	| score \
-	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
 	| sh64 | sh64le \
-	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
-	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
-	| spu | strongarm \
+	| sparc | sparc64 | sparc86x | sparclet | sparclite | sparcv9 | sparcv9b \
+	| strongarm \
 	| tahoe | thumb | tic4x | tic80 | tron \
-	| ubicom32 \
 	| v850 | v850e \
 	| we32k \
-	| x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \
-	| z8k | z80)
+	| x86 | xscale | xstormy16 | xtensa \
+	| z8k)
 		basic_machine=$basic_machine-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12 | picochip)
+	m6811 | m68hc11 | m6812 | m68hc12)
 		# Motorola 68HC11/12.
 		basic_machine=$basic_machine-unknown
 		os=-none
 		;;
 	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
 		;;
-	ms1)
-		basic_machine=mt-unknown
-		;;
 
 	# We use `pc' rather than `unknown'
 	# because (1) that's what they normally are, and
@@ -329,70 +292,56 @@ case $basic_machine in
 	| a29k-* \
 	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
-	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | amd64-* | arc-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
-	| avr-* | avr32-* \
-	| bfin-* | bs2000-* \
+	| avr-* \
+	| bs2000-* \
 	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
-	| clipper-* | craynv-* | cydra-* \
+	| clipper-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
-	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+	| f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
-	| ip2k-* | iq2000-* \
-	| lm32-* \
-	| m32c-* | m32r-* | m32rle-* \
+	| ip2k-* \
+	| m32r-* \
 	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \
+	| m88110-* | m88k-* | mcore-* \
 	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
 	| mips16-* \
 	| mips64-* | mips64el-* \
-	| mips64octeon-* | mips64octeonel-* \
-	| mips64orion-* | mips64orionel-* \
-	| mips64r5900-* | mips64r5900el-* \
 	| mips64vr-* | mips64vrel-* \
+	| mips64orion-* | mips64orionel-* \
 	| mips64vr4100-* | mips64vr4100el-* \
 	| mips64vr4300-* | mips64vr4300el-* \
 	| mips64vr5000-* | mips64vr5000el-* \
-	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
 	| mipsisa64-* | mipsisa64el-* \
-	| mipsisa64r2-* | mipsisa64r2el-* \
 	| mipsisa64sb1-* | mipsisa64sb1el-* \
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
 	| mipstx39-* | mipstx39el-* \
-	| mmix-* \
-	| mt-* \
 	| msp430-* \
-	| nios-* | nios2-* \
-	| none-* | np1-* | ns16k-* | ns32k-* \
+	| none-* | np1-* | nv1-* | ns16k-* | ns32k-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
 	| pyramid-* \
-	| romp-* | rs6000-* | rx-* \
-	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+	| romp-* | rs6000-* \
+	| sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \
 	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
-	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
-	| sparclite-* \
-	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \
+	| sparc-* | sparc64-* | sparc86x-* | sparclet-* | sparclite-* \
+	| sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
 	| tahoe-* | thumb-* \
-	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* | tile-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
 	| tron-* \
-	| ubicom32-* \
 	| v850-* | v850e-* | vax-* \
 	| we32k-* \
-	| x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \
-	| xstormy16-* | xtensa*-* \
+	| x86-* | x86_64-* | xps100-* | xscale-* | xstormy16-* \
+	| xtensa-* \
 	| ymp-* \
-	| z8k-* | z80-*)
-		;;
-	# Recognize the basic CPU types without company name, with glob match.
-	xtensa*)
-		basic_machine=$basic_machine-unknown
+	| z8k-*)
 		;;
 	# Recognize the various machine names and aliases which stand
 	# for a CPU type and a company and sometimes even an OS.
@@ -410,9 +359,6 @@ case $basic_machine in
 		basic_machine=a29k-amd
 		os=-udi
 		;;
-    	abacus)
-		basic_machine=abacus-unknown
-		;;
 	adobe68k)
 		basic_machine=m68010-adobe
 		os=-scout
@@ -430,9 +376,6 @@ case $basic_machine in
 	amd64)
 		basic_machine=x86_64-pc
 		;;
-	amd64-*)
-		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
 	amdahl)
 		basic_machine=580-amdahl
 		os=-sysv
@@ -456,10 +399,6 @@ case $basic_machine in
 		basic_machine=m68k-apollo
 		os=-bsd
 		;;
-	aros)
-		basic_machine=i386-pc
-		os=-aros
-		;;
 	aux)
 		basic_machine=m68k-apple
 		os=-aux
@@ -468,26 +407,10 @@ case $basic_machine in
 		basic_machine=ns32k-sequent
 		os=-dynix
 		;;
-	blackfin)
-		basic_machine=bfin-unknown
-		os=-linux
-		;;
-	blackfin-*)
-		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
-		os=-linux
-		;;
-	bluegene*)
-		basic_machine=powerpc-ibm
-		os=-cnk
-		;;
 	c90)
 		basic_machine=c90-cray
 		os=-unicos
 		;;
-        cegcc)
-		basic_machine=arm-unknown
-		os=-cegcc
-		;;
 	convex-c1)
 		basic_machine=c1-convex
 		os=-bsd
@@ -512,27 +435,12 @@ case $basic_machine in
 		basic_machine=j90-cray
 		os=-unicos
 		;;
-	craynv)
-		basic_machine=craynv-cray
-		os=-unicosmp
-		;;
-	cr16)
-		basic_machine=cr16-unknown
-		os=-elf
-		;;
 	crds | unos)
 		basic_machine=m68k-crds
 		;;
-	crisv32 | crisv32-* | etraxfs*)
-		basic_machine=crisv32-axis
-		;;
 	cris | cris-* | etrax*)
 		basic_machine=cris-axis
 		;;
-	crx)
-		basic_machine=crx-unknown
-		os=-elf
-		;;
 	da30 | da30-*)
 		basic_machine=m68k-da30
 		;;
@@ -555,14 +463,6 @@ case $basic_machine in
 		basic_machine=m88k-motorola
 		os=-sysv3
 		;;
-	dicos)
-		basic_machine=i686-pc
-		os=-dicos
-		;;
-	djgpp)
-		basic_machine=i586-pc
-		os=-msdosdjgpp
-		;;
 	dpx20 | dpx20-*)
 		basic_machine=rs6000-bull
 		os=-bosx
@@ -713,14 +613,6 @@ case $basic_machine in
 		basic_machine=m68k-isi
 		os=-sysv
 		;;
-	m68knommu)
-		basic_machine=m68k-unknown
-		os=-linux
-		;;
-	m68knommu-*)
-		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
-		os=-linux
-		;;
 	m88k-omron*)
 		basic_machine=m88k-omron
 		;;
@@ -732,17 +624,10 @@ case $basic_machine in
 		basic_machine=ns32k-utek
 		os=-sysv
 		;;
-        microblaze)
-		basic_machine=microblaze-xilinx
-		;;
 	mingw32)
 		basic_machine=i386-pc
 		os=-mingw32
 		;;
-	mingw32ce)
-		basic_machine=arm-unknown
-		os=-mingw32ce
-		;;
 	miniframe)
 		basic_machine=m68000-convergent
 		;;
@@ -756,6 +641,10 @@ case $basic_machine in
 	mips3*)
 		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
 		;;
+	mmix*)
+		basic_machine=mmix-knuth
+		os=-mmixware
+		;;
 	monitor)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -768,9 +657,6 @@ case $basic_machine in
 		basic_machine=i386-pc
 		os=-msdos
 		;;
-	ms1-*)
-		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
-		;;
 	mvs)
 		basic_machine=i370-ibm
 		os=-mvs
@@ -839,6 +725,10 @@ case $basic_machine in
 	np1)
 		basic_machine=np1-gould
 		;;
+	nv1)
+		basic_machine=nv1-cray
+		os=-unicosmp
+		;;
 	nsr-tandem)
 		basic_machine=nsr-tandem
 		;;
@@ -846,12 +736,9 @@ case $basic_machine in
 		basic_machine=hppa1.1-oki
 		os=-proelf
 		;;
-	openrisc | openrisc-*)
+	or32 | or32-*)
 		basic_machine=or32-unknown
-		;;
-	os400)
-		basic_machine=powerpc-ibm
-		os=-os400
+		os=-coff
 		;;
 	OSE68000 | ose68000)
 		basic_machine=m68000-ericsson
@@ -869,14 +756,6 @@ case $basic_machine in
 		basic_machine=i860-intel
 		os=-osf
 		;;
-	parisc)
-		basic_machine=hppa-unknown
-		os=-linux
-		;;
-	parisc-*)
-		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
-		os=-linux
-		;;
 	pbd)
 		basic_machine=sparc-tti
 		;;
@@ -886,12 +765,6 @@ case $basic_machine in
 	pc532 | pc532-*)
 		basic_machine=ns32k-pc532
 		;;
-	pc98)
-		basic_machine=i386-pc
-		;;
-	pc98-*)
-		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
 	pentium | p5 | k5 | k6 | nexgen | viac3)
 		basic_machine=i586-pc
 		;;
@@ -948,10 +821,6 @@ case $basic_machine in
 		basic_machine=i586-unknown
 		os=-pw32
 		;;
-	rdos)
-		basic_machine=i386-pc
-		os=-rdos
-		;;
 	rom68k)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -978,10 +847,6 @@ case $basic_machine in
 	sb1el)
 		basic_machine=mipsisa64sb1el-unknown
 		;;
-	sde)
-		basic_machine=mipsisa32-sde
-		os=-elf
-		;;
 	sei)
 		basic_machine=mips-sei
 		os=-seiux
@@ -993,9 +858,6 @@ case $basic_machine in
 		basic_machine=sh-hitachi
 		os=-hms
 		;;
-	sh5el)
-		basic_machine=sh5le-unknown
-		;;
 	sh64)
 		basic_machine=sh64-unknown
 		;;
@@ -1085,10 +947,6 @@ case $basic_machine in
 		basic_machine=tic6x-unknown
 		os=-coff
 		;;
-	tile*)
-		basic_machine=tile-unknown
-		os=-linux-gnu
-		;;
 	tx39)
 		basic_machine=mipstx39-unknown
 		;;
@@ -1102,10 +960,6 @@ case $basic_machine in
 	tower | tower-32)
 		basic_machine=m68k-ncr
 		;;
-	tpf)
-		basic_machine=s390x-ibm
-		os=-tpf
-		;;
 	udi29k)
 		basic_machine=a29k-amd
 		os=-udi
@@ -1149,10 +1003,6 @@ case $basic_machine in
 		basic_machine=hppa1.1-winbond
 		os=-proelf
 		;;
-	xbox)
-		basic_machine=i686-pc
-		os=-mingw32
-		;;
 	xps | xps100)
 		basic_machine=xps100-honeywell
 		;;
@@ -1164,10 +1014,6 @@ case $basic_machine in
 		basic_machine=z8k-unknown
 		os=-sim
 		;;
-	z80-*-coff)
-		basic_machine=z80-unknown
-		os=-sim
-		;;
 	none)
 		basic_machine=none-none
 		os=-none
@@ -1187,9 +1033,6 @@ case $basic_machine in
 	romp)
 		basic_machine=romp-ibm
 		;;
-	mmix)
-		basic_machine=mmix-knuth
-		;;
 	rs6000)
 		basic_machine=rs6000-ibm
 		;;
@@ -1206,10 +1049,13 @@ case $basic_machine in
 	we32k)
 		basic_machine=we32k-att
 		;;
-	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+	sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele)
 		basic_machine=sh-unknown
 		;;
-	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+	sh64)
+		basic_machine=sh64-unknown
+		;;
+	sparc | sparcv9 | sparcv9b)
 		basic_machine=sparc-sun
 		;;
 	cydra)
@@ -1256,9 +1102,6 @@ case $os in
         # First match some system type aliases
         # that might get confused with valid system types.
 	# -solaris* is a basic system type, with this one exception.
-        -auroraux)
-	        os=-auroraux
-		;;
 	-solaris1 | -solaris1.*)
 		os=`echo $os | sed -e 's|solaris1|sunos4|'`
 		;;
@@ -1279,30 +1122,25 @@ case $os in
 	# Each alternative MUST END IN A *, to match a version number.
 	# -sysv* is not here because it comes later, after sysvr4.
 	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
-	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
-	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
-	      | -sym* | -kopensolaris* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-	      | -aos* | -aros* \
+	      | -aos* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
-	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
-	      | -openbsd* | -solidbsd* \
-	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
-	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -hiux* | -386bsd* | -netbsd* | -openbsd* | -kfreebsd* | -freebsd* | -riscix* \
+	      | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
 	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
 	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
-	      | -chorusos* | -chorusrdb* | -cegcc* \
+	      | -chorusos* | -chorusrdb* \
 	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
-	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \
 	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
-	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1320,15 +1158,12 @@ case $os in
 		os=`echo $os | sed -e 's|nto|nto-qnx|'`
 		;;
 	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
-	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
 	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
 		;;
 	-mac*)
 		os=`echo $os | sed -e 's|mac|macos|'`
 		;;
-	-linux-dietlibc)
-		os=-linux-dietlibc
-		;;
 	-linux*)
 		os=`echo $os | sed -e 's|linux|linux-gnu|'`
 		;;
@@ -1341,9 +1176,6 @@ case $os in
 	-opened*)
 		os=-openedition
 		;;
-        -os400*)
-		os=-os400
-		;;
 	-wince*)
 		os=-wince
 		;;
@@ -1365,9 +1197,6 @@ case $os in
 	-atheos*)
 		os=-atheos
 		;;
-	-syllable*)
-		os=-syllable
-		;;
 	-386bsd)
 		os=-bsd
 		;;
@@ -1390,9 +1219,6 @@ case $os in
 	-sinix*)
 		os=-sysv4
 		;;
-        -tpf*)
-		os=-tpf
-		;;
 	-triton*)
 		os=-sysv3
 		;;
@@ -1429,12 +1255,6 @@ case $os in
 	-kaos*)
 		os=-kaos
 		;;
-	-zvmoe)
-		os=-zvmoe
-		;;
-	-dicos*)
-		os=-dicos
-		;;
 	-none)
 		;;
 	*)
@@ -1457,12 +1277,6 @@ else
 # system, and we'll never get to this point.
 
 case $basic_machine in
-        score-*)
-		os=-elf
-		;;
-        spu-*)
-		os=-elf
-		;;
 	*-acorn)
 		os=-riscix1.2
 		;;
@@ -1472,9 +1286,9 @@ case $basic_machine in
 	arm*-semi)
 		os=-aout
 		;;
-        c4x-* | tic4x-*)
-        	os=-coff
-		;;
+    c4x-* | tic4x-*)
+        os=-coff
+        ;;
 	# This must come before the *-dec entry.
 	pdp10-*)
 		os=-tops20
@@ -1500,9 +1314,6 @@ case $basic_machine in
 	m68*-cisco)
 		os=-aout
 		;;
-        mep-*)
-		os=-elf
-		;;
 	mips*-cisco)
 		os=-elf
 		;;
@@ -1521,15 +1332,9 @@ case $basic_machine in
 	*-be)
 		os=-beos
 		;;
-	*-haiku)
-		os=-haiku
-		;;
 	*-ibm)
 		os=-aix
 		;;
-    	*-knuth)
-		os=-mmixware
-		;;
 	*-wec)
 		os=-proelf
 		;;
@@ -1632,7 +1437,7 @@ case $basic_machine in
 			-sunos*)
 				vendor=sun
 				;;
-			-cnk*|-aix*)
+			-aix*)
 				vendor=ibm
 				;;
 			-beos*)
@@ -1662,15 +1467,9 @@ case $basic_machine in
 			-mvs* | -opened*)
 				vendor=ibm
 				;;
-			-os400*)
-				vendor=ibm
-				;;
 			-ptx*)
 				vendor=sequent
 				;;
-			-tpf*)
-				vendor=ibm
-				;;
 			-vxsim* | -vxworks* | -windiss*)
 				vendor=wrs
 				;;
@@ -1695,7 +1494,7 @@ case $basic_machine in
 esac
 
 echo $basic_machine$os
-exit
+exit 0
 
 # Local variables:
 # eval: (add-hook 'write-file-hooks 'time-stamp)
diff --git a/configure b/configure
index 1797513..a7929a6 100755
--- a/configure
+++ b/configure
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.68 for ffms2 2.15.4.2.
+# Generated by GNU Autoconf 2.68 for ffms2 2.16.3.
 #
 #
 # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
@@ -567,8 +567,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='ffms2'
 PACKAGE_TARNAME='ffms2'
-PACKAGE_VERSION='2.15.4.2'
-PACKAGE_STRING='ffms2 2.15.4.2'
+PACKAGE_VERSION='2.16.3'
+PACKAGE_STRING='ffms2 2.16.3'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -624,11 +624,8 @@ AM_MAKEFLAGS
 MAKEFLAGS
 shavedir
 LTUNDEF
-POSTPROC_LIBS
-POSTPROC_CFLAGS
-postproc
-FFMPEG_LIBS
-FFMPEG_CFLAGS
+LIBAV_LIBS
+LIBAV_CFLAGS
 pkgconfigdir
 PKG_CONFIG_LIBDIR
 PKG_CONFIG_PATH
@@ -758,6 +755,7 @@ ac_subst_files=''
 ac_user_opts='
 enable_option_checking
 enable_maintainer_mode
+enable_debug
 enable_dependency_tracking
 enable_static
 enable_shared
@@ -767,7 +765,6 @@ with_gnu_ld
 with_sysroot
 enable_libtool_lock
 with_zlib
-enable_postproc
 enable_shave
 '
       ac_precious_vars='build_alias
@@ -786,10 +783,8 @@ CXXCPP
 PKG_CONFIG
 PKG_CONFIG_PATH
 PKG_CONFIG_LIBDIR
-FFMPEG_CFLAGS
-FFMPEG_LIBS
-POSTPROC_CFLAGS
-POSTPROC_LIBS'
+LIBAV_CFLAGS
+LIBAV_LIBS'
 
 
 # Initialize some variables set by options.
@@ -1332,7 +1327,7 @@ if test "$ac_init_help" = "long"; then
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures ffms2 2.15.4.2 to adapt to many kinds of systems.
+\`configure' configures ffms2 2.16.3 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1402,7 +1397,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of ffms2 2.15.4.2:";;
+     short | recursive ) echo "Configuration of ffms2 2.16.3:";;
    esac
   cat <<\_ACEOF
 
@@ -1412,6 +1407,7 @@ Optional Features:
   --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
   --enable-maintainer-mode  enable make rules and dependencies not useful
 			  (and sometimes confusing) to the casual installer
+  --enable-debug          Enable debug build. [default=no]
   --disable-dependency-tracking  speeds up one-time build
   --enable-dependency-tracking   do not reject slow dependency extractors
   --enable-static[=PKGS]  build static libraries [default=yes]
@@ -1419,8 +1415,6 @@ Optional Features:
   --enable-fast-install[=PKGS]
                           optimize for fast installation [default=yes]
   --disable-libtool-lock  avoid locking (might break parallel builds)
-  --enable-postproc       Enable postproc support in FFMS2. Changes license to
-                          GPL [default=no].
   --enable-shave          use shave to make the build pretty [[default=yes]]
 
 Optional Packages:
@@ -1450,13 +1444,9 @@ Some influential environment variables:
               directories to add to pkg-config's search path
   PKG_CONFIG_LIBDIR
               path overriding pkg-config's built-in search path
-  FFMPEG_CFLAGS
-              C compiler flags for FFMPEG, overriding pkg-config
-  FFMPEG_LIBS linker flags for FFMPEG, overriding pkg-config
-  POSTPROC_CFLAGS
-              C compiler flags for POSTPROC, overriding pkg-config
-  POSTPROC_LIBS
-              linker flags for POSTPROC, overriding pkg-config
+  LIBAV_CFLAGS
+              C compiler flags for LIBAV, overriding pkg-config
+  LIBAV_LIBS  linker flags for LIBAV, overriding pkg-config
 
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
@@ -1524,7 +1514,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-ffms2 configure 2.15.4.2
+ffms2 configure 2.16.3
 generated by GNU Autoconf 2.68
 
 Copyright (C) 2010 Free Software Foundation, Inc.
@@ -2064,7 +2054,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by ffms2 $as_me 2.15.4.2, which was
+It was created by ffms2 $as_me 2.16.3, which was
 generated by GNU Autoconf 2.68.  Invocation command line was
 
   $ $0 $@
@@ -2881,7 +2871,7 @@ fi
 
 # Define the identity of the package.
  PACKAGE='ffms2'
- VERSION='2.15.4.2'
+ VERSION='2.16.3'
 
 
 cat >>confdefs.h <<_ACEOF
@@ -2945,12 +2935,33 @@ fi
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if debug build is enabled" >&5
+$as_echo_n "checking if debug build is enabled... " >&6; }
+
+# Check whether --enable-debug was given.
+if test "${enable_debug+set}" = set; then :
+  enableval=$enable_debug; enable_debug=yes
+else
+  enable_debug=no
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_debug" >&5
+$as_echo "$enable_debug" >&6; }
+
+if test "$enable_debug" = yes; then
+    OPT_FLAGS="-O0 -g"
+else
+    OPT_FLAGS="-O3"
+fi
+
 if test -z "$CFLAGS"; then
-    CFLAGS="-O3"
+    CFLAGS="$OPT_FLAGS"
 fi
 
 if test -z "$CXXFLAGS"; then
-    CXXFLAGS="-O3"
+    CXXFLAGS="$OPT_FLAGS"
 fi
 
 ac_config_headers="$ac_config_headers src/config/config.h"
@@ -9655,10 +9666,6 @@ fi
       hardcode_shlibpath_var=no
       ;;
 
-    freebsd1*)
-      ld_shlibs=no
-      ;;
-
     # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
     # support.  Future versions do this automatically, but an explicit c++rt0.o
     # does not break anything, and helps significantly (at the cost of a little
@@ -9671,7 +9678,7 @@ fi
       ;;
 
     # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
+    freebsd2.*)
       archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
       hardcode_direct=yes
       hardcode_minus_L=yes
@@ -10649,10 +10656,6 @@ dgux*)
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
-freebsd1*)
-  dynamic_linker=no
-  ;;
-
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
@@ -10660,7 +10663,7 @@ freebsd* | dragonfly*)
     objformat=`/usr/bin/objformat`
   else
     case $host_os in
-    freebsd[123]*) objformat=aout ;;
+    freebsd[23].*) objformat=aout ;;
     *) objformat=elf ;;
     esac
   fi
@@ -10678,7 +10681,7 @@ freebsd* | dragonfly*)
   esac
   shlibpath_var=LD_LIBRARY_PATH
   case $host_os in
-  freebsd2*)
+  freebsd2.*)
     shlibpath_overrides_runpath=yes
     ;;
   freebsd3.[01]* | freebsdelf3.[01]*)
@@ -12618,7 +12621,7 @@ fi
         esac
         ;;
 
-      freebsd[12]*)
+      freebsd2.*)
         # C++ shared libraries reported to be fairly broken before
 	# switch to ELF
         ld_shlibs_CXX=no
@@ -14482,10 +14485,6 @@ dgux*)
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
-freebsd1*)
-  dynamic_linker=no
-  ;;
-
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
@@ -14493,7 +14492,7 @@ freebsd* | dragonfly*)
     objformat=`/usr/bin/objformat`
   else
     case $host_os in
-    freebsd[123]*) objformat=aout ;;
+    freebsd[23].*) objformat=aout ;;
     *) objformat=elf ;;
     esac
   fi
@@ -14511,7 +14510,7 @@ freebsd* | dragonfly*)
   esac
   shlibpath_var=LD_LIBRARY_PATH
   case $host_os in
-  freebsd2*)
+  freebsd2.*)
     shlibpath_overrides_runpath=yes
     ;;
   freebsd3.[01]* | freebsdelf3.[01]*)
@@ -15266,6 +15265,51 @@ fi
 FFMS_VERSION="$(sh $(dirname -- "$0")/version.sh)"
 
 
+_CXXFLAGS="$CXXFLAGS"
+CXXFLAGS="$CXXFLAGS -fvisibility=hidden"
+
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if -fvisibility=hidden works" >&5
+$as_echo_n "checking if -fvisibility=hidden works... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+char foo;
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_cxx_try_compile "$LINENO"; then :
+  fvisibility_works=yes
+else
+  fvisibility_works=no
+
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $fvisibility_works" >&5
+$as_echo "$fvisibility_works" >&6; }
+
+if test "$fvisibility_works" = no; then
+    CXXFLAGS="$_CXXFLAGS"
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
 
 
 # Check whether --with-zlib was given.
@@ -15368,11 +15412,17 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
                #include <objbase.h>
-               int main() {
+
+int
+main ()
+{
+
                    CoUninitialize();
                    return 0;
-               }
 
+  ;
+  return 0;
+}
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
@@ -15394,7 +15444,6 @@ _LIBS="$LIBS"
 
 
 
-
 if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
 	if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args.
@@ -15513,37 +15562,35 @@ pkgconfigdir="\$(libdir)/pkgconfig"
 
 
 pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for FFMPEG" >&5
-$as_echo_n "checking for FFMPEG... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for LIBAV" >&5
+$as_echo_n "checking for LIBAV... " >&6; }
 
-if test -n "$FFMPEG_CFLAGS"; then
-    pkg_cv_FFMPEG_CFLAGS="$FFMPEG_CFLAGS"
+if test -n "$LIBAV_CFLAGS"; then
+    pkg_cv_LIBAV_CFLAGS="$LIBAV_CFLAGS"
  elif test -n "$PKG_CONFIG"; then
     if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 \""; } >&5
-  ($PKG_CONFIG --exists --print-errors "libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 ") 2>&5
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 \""; } >&5
+  ($PKG_CONFIG --exists --print-errors "libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 ") 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-  pkg_cv_FFMPEG_CFLAGS=`$PKG_CONFIG --cflags "libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 " 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
+  pkg_cv_LIBAV_CFLAGS=`$PKG_CONFIG --cflags "libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 " 2>/dev/null`
 else
   pkg_failed=yes
 fi
  else
     pkg_failed=untried
 fi
-if test -n "$FFMPEG_LIBS"; then
-    pkg_cv_FFMPEG_LIBS="$FFMPEG_LIBS"
+if test -n "$LIBAV_LIBS"; then
+    pkg_cv_LIBAV_LIBS="$LIBAV_LIBS"
  elif test -n "$PKG_CONFIG"; then
     if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 \""; } >&5
-  ($PKG_CONFIG --exists --print-errors "libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 ") 2>&5
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 \""; } >&5
+  ($PKG_CONFIG --exists --print-errors "libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 ") 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-  pkg_cv_FFMPEG_LIBS=`$PKG_CONFIG --libs "libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 " 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
+  pkg_cv_LIBAV_LIBS=`$PKG_CONFIG --libs "libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 " 2>/dev/null`
 else
   pkg_failed=yes
 fi
@@ -15563,22 +15610,22 @@ else
         _pkg_short_errors_supported=no
 fi
         if test $_pkg_short_errors_supported = yes; then
-	        FFMPEG_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 " 2>&1`
+	        LIBAV_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 " 2>&1`
         else
-	        FFMPEG_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 " 2>&1`
+	        LIBAV_PKG_ERRORS=`$PKG_CONFIG --print-errors "libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 " 2>&1`
         fi
 	# Put the nasty error message in config.log where it belongs
-	echo "$FFMPEG_PKG_ERRORS" >&5
+	echo "$LIBAV_PKG_ERRORS" >&5
 
-	as_fn_error $? "Package requirements (libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 ) were not met:
+	as_fn_error $? "Package requirements (libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 ) were not met:
 
-$FFMPEG_PKG_ERRORS
+$LIBAV_PKG_ERRORS
 
 Consider adjusting the PKG_CONFIG_PATH environment variable if you
 installed software in a non-standard prefix.
 
-Alternatively, you may set the environment variables FFMPEG_CFLAGS
-and FFMPEG_LIBS to avoid the need to call pkg-config.
+Alternatively, you may set the environment variables LIBAV_CFLAGS
+and LIBAV_LIBS to avoid the need to call pkg-config.
 See the pkg-config man page for more details." "$LINENO" 5
 elif test $pkg_failed = untried; then
      	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
@@ -15589,15 +15636,15 @@ as_fn_error $? "The pkg-config script could not be found or is too old.  Make su
 is in your PATH or set the PKG_CONFIG environment variable to the full
 path to pkg-config.
 
-Alternatively, you may set the environment variables FFMPEG_CFLAGS
-and FFMPEG_LIBS to avoid the need to call pkg-config.
+Alternatively, you may set the environment variables LIBAV_CFLAGS
+and LIBAV_LIBS to avoid the need to call pkg-config.
 See the pkg-config man page for more details.
 
 To get pkg-config, see <http://pkg-config.freedesktop.org/>.
 See \`config.log' for more details" "$LINENO" 5; }
 else
-	FFMPEG_CFLAGS=$pkg_cv_FFMPEG_CFLAGS
-	FFMPEG_LIBS=$pkg_cv_FFMPEG_LIBS
+	LIBAV_CFLAGS=$pkg_cv_LIBAV_CFLAGS
+	LIBAV_LIBS=$pkg_cv_LIBAV_LIBS
         { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 $as_echo "yes" >&6; }
 
@@ -15608,190 +15655,93 @@ CPPFLAGS="$CPPFLAGS -D__STDC_CONSTANT_MACROS"
 
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether FFmpeg/Libav works" >&5
-$as_echo_n "checking whether FFmpeg/Libav works... " >&6; }
-CFLAGS="$_CFLAGS $FFMPEG_CFLAGS"
-LIBS="$_LIBS $FFMPEG_LIBS"
-
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether linking with FFmpeg or Libav" >&5
+$as_echo_n "checking whether linking with FFmpeg or Libav... " >&6; }
+CFLAGS="$_CFLAGS $LIBAV_CFLAGS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
             #include <libavcodec/avcodec.h>
             #include <libswscale/swscale.h>
-            int main() {
-                avcodec_init();
-                swscale_version();
-                return 0;
-            }
+
+int
+main ()
+{
+
+                #if LIBAVCODEC_VERSION_MICRO >= 100
+                /* is ffmpeg */
+                #elif LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 47, 100)
+                /* hopefully libav doesn''t add G2M before 53.47.... */
+                (void)CODEC_ID_G2M;
+                #else
+                #error is libav or old enough that the distinction doesn't matter
+                #endif
+
+  ;
+  return 0;
+}
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
-  eval FFMPEG_WORKS=yes
+  eval FFMS_USE_FFMPEG_COMPAT=yes
 else
-  eval FFMPEG_WORKS=no
+  eval FFMS_USE_FFMPEG_COMPAT=no
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $FFMPEG_WORKS" >&5
-$as_echo "$FFMPEG_WORKS" >&6; }
-if test "$FFMPEG_WORKS" = no; then
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot link with FFmpeg/Libav
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether postproc was enabled" >&5
-$as_echo_n "checking whether postproc was enabled... " >&6; }
-
-# Check whether --enable-postproc was given.
-if test "${enable_postproc+set}" = set; then :
-  enableval=$enable_postproc; enable_postproc=yes
-else
-  enable_postproc=no
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_postproc" >&5
-$as_echo "$enable_postproc" >&6; }
-
-
-
-if test "$enable_postproc" = yes; then
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for POSTPROC" >&5
-$as_echo_n "checking for POSTPROC... " >&6; }
-
-if test -n "$POSTPROC_CFLAGS"; then
-    pkg_cv_POSTPROC_CFLAGS="$POSTPROC_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libpostproc >= 51.2.0\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "libpostproc >= 51.2.0") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_POSTPROC_CFLAGS=`$PKG_CONFIG --cflags "libpostproc >= 51.2.0" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$POSTPROC_LIBS"; then
-    pkg_cv_POSTPROC_LIBS="$POSTPROC_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libpostproc >= 51.2.0\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "libpostproc >= 51.2.0") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_POSTPROC_LIBS=`$PKG_CONFIG --libs "libpostproc >= 51.2.0" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
 
+if test "$FFMS_USE_FFMPEG_COMPAT" = yes; then
 
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+$as_echo "#define FFMS_USE_FFMPEG_COMPAT 1" >>confdefs.h
 
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
+   _lav_name=FFmpeg
 else
-        _pkg_short_errors_supported=no
+   _lav_name=Libav
 fi
-        if test $_pkg_short_errors_supported = yes; then
-	        POSTPROC_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libpostproc >= 51.2.0" 2>&1`
-        else
-	        POSTPROC_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libpostproc >= 51.2.0" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$POSTPROC_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (libpostproc >= 51.2.0) were not met:
-
-$POSTPROC_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables POSTPROC_CFLAGS
-and POSTPROC_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables POSTPROC_CFLAGS
-and POSTPROC_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	POSTPROC_CFLAGS=$pkg_cv_POSTPROC_CFLAGS
-	POSTPROC_LIBS=$pkg_cv_POSTPROC_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-
-fi
-
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $_lav_name" >&5
+$as_echo "$_lav_name" >&6; }
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $_lav_name works" >&5
+$as_echo_n "checking whether $_lav_name works... " >&6; }
+LIBS="$_LIBS $LIBAV_LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether postproc works" >&5
-$as_echo_n "checking whether postproc works... " >&6; }
-    CFLAGS="$_CFLAGS $POSTPROC_CFLAGS"
-    LIBS="$_LIBS $POSTPROC_LIBS"
+            #include <libavcodec/avcodec.h>
+            #include <libswscale/swscale.h>
 
-            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
+int
+main ()
+{
 
-                #include <libpostproc/postprocess.h>
+                avcodec_init();
+                swscale_version();
+                #ifdef FFMS_USE_FFMPEG_COMPAT
+                int bogus = CODEC_ID_G2M;
+                (void) bogus;
+                #endif
 
-                int main() {
-                    postproc_version();
-                    return 0;
-                }
+  ;
+  return 0;
+}
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
-  eval POSTPROC_WORKS=yes
+  eval LIBAV_WORKS=yes
 else
-  eval POSTPROC_WORKS=no
+  eval LIBAV_WORKS=no
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $POSTPROC_WORKS" >&5
-$as_echo "$POSTPROC_WORKS" >&6; }
-    if test "$POSTPROC_WORKS" = no; then
-        { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBAV_WORKS" >&5
+$as_echo "$LIBAV_WORKS" >&6; }
+if test "$LIBAV_WORKS" = no; then
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot link with postproc
+as_fn_error $? "cannot link with $_lav_name
 See \`config.log' for more details" "$LINENO" 5; }
-    fi
-
-    postproc="libpostproc"
-
-$as_echo "#define WITH_LIBPOSTPROC 1" >>confdefs.h
-
 fi
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -Wl,-Bsymbolic is needed" >&5
@@ -15799,17 +15749,26 @@ $as_echo_n "checking whether -Wl,-Bsymbolic is needed... " >&6; }
 if test "$enable_shared" = yes; then
     _LDFLAGS="$LDFLAGS"
     LDFLAGS="$LDFLAGS -shared $lt_prog_compiler_pic"
-
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
             #include <libavcodec/avcodec.h>
             #include <libswscale/swscale.h>
-            int main() {
+
+int
+main ()
+{
+
                 avcodec_init();
                 swscale_version();
-                return 0;
-            }
+                #ifdef FFMS_USE_FFMPEG_COMPAT
+                int bogus = CODEC_ID_G2M;
+                (void) bogus;
+                #endif
+
+  ;
+  return 0;
+}
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
   eval no_bsymbolic=yes
@@ -15821,17 +15780,26 @@ rm -f core conftest.err conftest.$ac_objext \
 
     if test "$no_bsymbolic" = "no"; then
         LDFLAGS="$LDFLAGS -Wl,-Bsymbolic"
-
         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
             #include <libavcodec/avcodec.h>
             #include <libswscale/swscale.h>
-            int main() {
+
+int
+main ()
+{
+
                 avcodec_init();
                 swscale_version();
-                return 0;
-            }
+                #ifdef FFMS_USE_FFMPEG_COMPAT
+                int bogus = CODEC_ID_G2M;
+                (void) bogus;
+                #endif
+
+  ;
+  return 0;
+}
 _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
   eval bsymbolic=yes
@@ -16508,7 +16476,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by ffms2 $as_me 2.15.4.2, which was
+This file was extended by ffms2 $as_me 2.16.3, which was
 generated by GNU Autoconf 2.68.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -16574,7 +16542,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-ffms2 config.status 2.15.4.2
+ffms2 config.status 2.16.3
 configured by $0, generated by GNU Autoconf 2.68,
   with options \\"\$ac_cs_config\\"
 
diff --git a/configure.in b/configure.in
index 4700a24..6cbb2f0 100644
--- a/configure.in
+++ b/configure.in
@@ -5,12 +5,29 @@ AC_CONFIG_MACRO_DIR([m4])
 AM_INIT_AUTOMAKE([subdir-objects])
 AM_MAINTAINER_MODE([disable])
 
+AC_MSG_CHECKING([if debug build is enabled])
+
+AC_ARG_ENABLE([debug],
+        [AC_HELP_STRING([--enable-debug],
+            [Enable debug build. [default=no]])],
+        [enable_debug=yes],
+        [enable_debug=no]
+        )
+
+AC_MSG_RESULT([$enable_debug])
+
+if test "$enable_debug" = yes; then
+    OPT_FLAGS="-O0 -g"
+else
+    OPT_FLAGS="-O3"
+fi
+
 if test -z "$CFLAGS"; then
-    CFLAGS="-O3"
+    CFLAGS="$OPT_FLAGS"
 fi
 
 if test -z "$CXXFLAGS"; then
-    CXXFLAGS="-O3"
+    CXXFLAGS="$OPT_FLAGS"
 fi
 
 AM_CONFIG_HEADER([src/config/config.h])
@@ -39,18 +56,36 @@ fi
 FFMS_VERSION="$(sh $(dirname -- "$0")/version.sh)"
 AC_SUBST([FFMS_VERSION])
 
+_CXXFLAGS="$CXXFLAGS"
+CXXFLAGS="$CXXFLAGS -fvisibility=hidden"
+
+AC_LANG_PUSH([C++])
+
+AC_MSG_CHECKING([if -fvisibility=hidden works])
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([char foo;])],
+    [fvisibility_works=yes],
+    [fvisibility_works=no]
+    )
+
+AC_MSG_RESULT([$fvisibility_works])
+
+if test "$fvisibility_works" = no; then
+    CXXFLAGS="$_CXXFLAGS"
+fi
+
+AC_LANG_POP([C++])
+
 CHECK_ZLIB
 
 AC_MSG_CHECKING([for CoUninitialize in -lole32])
 _LIBS="$LIBS"
 LIBS="-lole32 $LIBS"
-AC_LINK_IFELSE([
+AC_LINK_IFELSE([AC_LANG_PROGRAM([[
                #include <objbase.h>
-               int main() {
+               ]],[[
                    CoUninitialize();
                    return 0;
-               }
-               ], [AC_MSG_RESULT([yes])], [LIBS="$_LIBS"; AC_MSG_RESULT([no])])
+               ]])], [AC_MSG_RESULT([yes])], [LIBS="$_LIBS"; AC_MSG_RESULT([no])])
 
 
 dnl Save CFLAGS and LIBS for later, as anything else we add will be from pkg-config
@@ -62,81 +97,69 @@ PKG_PROG_PKG_CONFIG([0.22])
 pkgconfigdir="\$(libdir)/pkgconfig"
 AC_SUBST(pkgconfigdir)
 
-PKG_CHECK_MODULES(FFMPEG, [libavformat >= 52.39.0 libavcodec >= 52.38.0 libswscale >= 0.7.0 libavutil >= 50.4.0 ])
+PKG_CHECK_MODULES(LIBAV, [libavformat >= 52.64.2 libavcodec >= 52.72.0 libswscale >= 0.7.0 libavutil >= 50.15.1 ])
 CPPFLAGS="$CPPFLAGS -D__STDC_CONSTANT_MACROS"
-AC_SUBST([FFMPEG_CFLAGS])
-AC_SUBST([FFMPEG_LIBS])
+AC_SUBST([LIBAV_CFLAGS])
+AC_SUBST([LIBAV_LIBS])
 
-AC_DEFUN([TEST_FFMPEG], [
-        AC_LINK_IFELSE([
+AC_DEFUN([TEST_IS_FFMPEG],
+         [AC_LINK_IFELSE([AC_LANG_PROGRAM([[
             #include <libavcodec/avcodec.h>
             #include <libswscale/swscale.h>
-            int main() {
-                avcodec_init();
-                swscale_version();
-                return 0;
-            }], [eval $1=yes], [eval $1=no])
+            ]],[[
+                #if LIBAVCODEC_VERSION_MICRO >= 100
+                /* is ffmpeg */
+                #elif LIBAVCODEC_VERSION_INT < AV_VERSION_INT(53, 47, 100)
+                /* hopefully libav doesn''t add G2M before 53.47.... */
+                (void)CODEC_ID_G2M;
+                #else
+                #error is libav or old enough that the distinction doesn't matter
+                #endif
+            ]])], [eval $1=yes], [eval $1=no])
         ])
 
-AC_MSG_CHECKING([whether FFmpeg/Libav works])
-CFLAGS="$_CFLAGS $FFMPEG_CFLAGS"
-LIBS="$_LIBS $FFMPEG_LIBS"
-TEST_FFMPEG([FFMPEG_WORKS])
-AC_MSG_RESULT([$FFMPEG_WORKS])
-if test "$FFMPEG_WORKS" = no; then
-    AC_MSG_FAILURE([cannot link with FFmpeg/Libav])
-fi
+AC_MSG_CHECKING([whether linking with FFmpeg or Libav])
+CFLAGS="$_CFLAGS $LIBAV_CFLAGS"
+TEST_IS_FFMPEG([FFMS_USE_FFMPEG_COMPAT])
 
-AC_MSG_CHECKING([whether postproc was enabled])
-
-AC_ARG_ENABLE([postproc],
-        [AC_HELP_STRING([--enable-postproc],
-            [Enable postproc support in FFMS2. Changes license to GPL [default=no].])],
-        [enable_postproc=yes],
-        [enable_postproc=no]
-        )
-
-AC_MSG_RESULT([$enable_postproc])
-
-AC_SUBST([postproc])
-
-if test "$enable_postproc" = yes; then
-
-    PKG_CHECK_MODULES(POSTPROC, [libpostproc >= 51.2.0])
-    AC_SUBST([POSTPROC_CFLAGS])
-    AC_SUBST([POSTPROC_LIBS])
-
-    AC_DEFUN([TEST_POSTPROC], [
-            AC_LINK_IFELSE([
-                #include <libpostproc/postprocess.h>
-
-                int main() {
-                    postproc_version();
-                    return 0;
-                }], [eval $1=yes], [eval $1=no])
-            ])
+if test "$FFMS_USE_FFMPEG_COMPAT" = yes; then
+   AC_DEFINE([FFMS_USE_FFMPEG_COMPAT], [1], [Building with FFmpeg?])
+   _lav_name=FFmpeg
+else
+   _lav_name=Libav
+fi
+AC_MSG_RESULT([$_lav_name])
 
-    AC_MSG_CHECKING([whether postproc works])
-    CFLAGS="$_CFLAGS $POSTPROC_CFLAGS"
-    LIBS="$_LIBS $POSTPROC_LIBS"
-    TEST_POSTPROC([POSTPROC_WORKS])
-    AC_MSG_RESULT([$POSTPROC_WORKS])
-    if test "$POSTPROC_WORKS" = no; then
-        AC_MSG_FAILURE([cannot link with postproc])
-    fi
+AC_DEFUN([TEST_LIBAV],
+         [AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+            #include <libavcodec/avcodec.h>
+            #include <libswscale/swscale.h>
+            ]],[[
+                avcodec_init();
+                swscale_version();
+                #ifdef FFMS_USE_FFMPEG_COMPAT
+                int bogus = CODEC_ID_G2M;
+                (void) bogus;
+                #endif
+            ]])], [eval $1=yes], [eval $1=no])
+        ])
 
-    postproc="libpostproc"
-    AC_DEFINE([WITH_LIBPOSTPROC], [1], [Building with postproc?])
+AC_MSG_CHECKING([whether $_lav_name works])
+LIBS="$_LIBS $LIBAV_LIBS"
+TEST_LIBAV([LIBAV_WORKS])
+AC_MSG_RESULT([$LIBAV_WORKS])
+if test "$LIBAV_WORKS" = no; then
+AC_MSG_FAILURE([cannot link with $_lav_name])
 fi
 
 AC_MSG_CHECKING([whether -Wl,-Bsymbolic is needed])
 if test "$enable_shared" = yes; then
     _LDFLAGS="$LDFLAGS"
     LDFLAGS="$LDFLAGS -shared $lt_prog_compiler_pic"
-    TEST_FFMPEG([no_bsymbolic])
+    TEST_LIBAV([no_bsymbolic])
     if test "$no_bsymbolic" = "no"; then
         LDFLAGS="$LDFLAGS -Wl,-Bsymbolic"
-        TEST_FFMPEG([bsymbolic])
+        TEST_LIBAV([bsymbolic])
         if test "$bsymbolic" = "yes"; then
             LDFLAGS="$_LDFLAGS -Wl,-Bsymbolic"
         else
diff --git a/doc/ffms2-api.html b/doc/ffms2-api.html
index ee9ab6a..91345ac 100644
--- a/doc/ffms2-api.html
+++ b/doc/ffms2-api.html
@@ -30,7 +30,7 @@ FFMS2 does not mux or encode anything. FFMS2 does not give you fine control over
 <ul><li>As new as possible. If it's older than version 0.6 it will mean definite failure.</li>
 <li>On Win32 you should REALLY, REALLY make sure to have a good compile of the pthreads library.</li>
 <li>Further recommended configuration options: <tt>--disable-debug --disable-muxers --disable-encoders --disable-filters --disable-hwaccels --disable-network --disable-devices --enable-runtime-cpudetect</tt> (runtime cpudetect in particular is a good idea if you are planning on distributing the library; not disabling debug results in a gigantic dll).</li>
-<li>If you want to use the postprocessing filter functionality (i.e. <tt>FFMS_SetPP()</tt>) you need to compile FFmpeg with libpostproc (pass <tt>--enable-gpl --enable-postproc</tt> to its configure). Note that this will make the FFMS2 binary GPL licensed.</li>
+<li>If you want to use the postprocessing filter functionality (i.e. <tt>FFMS_SetPP()</tt>) you need to compile FFmpeg with libpostproc (pass <tt>--enable-gpl --enable-postproc</tt> to its configure). Note that this will make the FFMS2 binary GPL licensed. Note that libpostproc support is deprecated and will go away some time in the future.</li>
 </ul>
 </li>
 <li><b><a href="http://www.zlib.net/">zlib</a></b></li>
@@ -40,10 +40,10 @@ Compiling the library itself is fairly straightforward. For the basics, just add
 </p>
 <h3>Windows-specific compilation notes</h3>
 <p>
-If you're compiling the library on Windows, it is suggested that you use the Microsoft Visual Studio 2008 solution file from SVN. Any version of MSVC2008 and MSVC2010 should work for compiling it, including the free Express Edition (but if you use that you must undefine HAALISOURCE or find a copy of the ATL libraries). The project file in question assumes that you have compiled FFmpeg with MinGW (guides on how to do that are easy to find) and want to link FFMS2 with it statically (linking it dynamically is possible but not recommended since it usually leads to DLL hell). Add your mingw/include and mingw/lib folders to MSVC's respective global directory settings (Tools menu -> Options -> Projects and Solutions -> VC++ Directories) and you should be good to go.
+If you're compiling the library on Windows, it is suggested that you use the Microsoft Visual Studio 2008 solution file from SVN. Any version of MSVC2008 and MSVC2010 should work for compiling it, including the free Express Edition (but if you use that you must undefine HAALISOURCE or find a copy of the ATL libraries). The project file in question assumes that you have compiled Libav with MinGW (guides on how to do that are easy to find) and want to link FFMS2 with it statically (linking it dynamically is possible but not recommended since it usually leads to DLL hell). If you're using FFmpeg (as opposed to Libav), uncomment #define FFMS_USE_FFMPEG_COMPAT in ffmscompat.h, as this is not always automatically detected. Add your mingw/include and mingw/lib folders to MSVC's respective global directory settings (Tools menu -> Options -> Projects and Solutions -> VC++ Directories) and you should be good to go.
 </p>
 <p>
-If you're targeting x64 from msvc just keep in mind that this method of building will probably take a little extra effort to get a working libav compile to link against.  As far as I know libav will have to be cross compiled from linux (haven't found any native mingw compilers that output the symbols correctly), there is a guide <b><a href="http://ffmpeg.arrozcru.org/wiki/index.php?title=Building_64-bit_static_libraries">here</a></b>.  Follow it all the way up to the compiling ffmpeg part and you can throw in the extra configure flags as defined above (also you'll <b>NEED</b> --extra-cflags="-D_SYSCRT" in order to get it to link correctly in msvc).  If you want pthreads support I recommend using something like <b><a href="https://github.com/TheRyuu/pw32threads">this pthread wrapper</a></b> for w32threads otherwise more linking trouble awaits you.  The rest is just like targeting 32bit.  Just add the appropriate directories to the VC directories (probably taken from /usr/local/x86_64-w64-mingw32 in this case).
+Targetting x64 from msvc requires a little extra work. You'll need a fairly recent mingw, and a libav which has w32threads, as x64 pthreads is a linking nightmare. Building libav for x64 is much like for 32-bit, except with the relevant prefix information (which will be along the lines of --prefix=/mingw/x86_64-w64-mingw32/ --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32), and --extra-cflags="-D_SYSCRT" is <b>required</b> for the end result to be linkable from msvc. Note that you'll probably need to add /usr/local/x86_64-w64-mingw32/... to MSVC's directories rather than the usual paths.
 </p>
 <p>
 If you're using anything else, you're on your own. It's possible to build the library using MinGW; there is an avisynth plugin available that uses the avisynth_c interface originally developed to target 64-bit avisynth (it is available in <tt>branches/c_plugin</tt> in svn). If you're rolling your own MSVC solution file, remember that you need to <tt>#define FFMS_EXPORTS</tt> somewhere when compiling the library. You may also <tt>#define HAALISOURCE</tt> if you want to make the library able to open MPEG TS/PS and OGM files using Haali's DirectShow splitter (if you do not define it, those files will be opened with libavformat instead, and that usually doesn't work out all that well). Note that if you do so, opening those files will fail unless the user has the <a href="http://haali.cs.msu.ru/mkv/">Haali Media Splitter</a> DirectShow filter installed. Both those defines are enabled by default in the solution file in SVN.
@@ -364,6 +364,7 @@ Resets the output format for the given <tt>FFMS_VideoSource</tt> object so that
 </p>
 
 <h3>FFMS_SetPP - sets postprocessing options</h3>
+<h5 class="deprecated">DEPRECATED</h5>
 <pre>int FFMS_SetPP(FFMS_VideoSource *V, const char *PP, FFMS_ErrorInfo *ErrorInfo)</pre>
 <p>
 Sets the postprocessing filter chain that will be applied to frames retrieved from the given <tt>FFMS_VideoSource</tt> object by all further calls to <tt>FFMS_GetFrame</tt> and <tt>FFMS_GetFrameByTime</tt> until the next call to <tt>FFMS_SetPP</tt> or <tt>FFMS_ResetPP</tt>. The filter chain is described by a text string; see the PP string format section below for details.
@@ -379,6 +380,7 @@ See above.</p>
 </p>
 
 <h3>FFMS_ResetPP - resets postprocessing options</h3>
+<h5 class="deprecated">DEPRECATED</h5>
 <pre>void FFMS_ResetPP(FFMS_VideoSource *V)</pre>
 <p>
 Resets the postprocessing filter chain that will be applied to frames retrieved from the given <tt>FFMS_VideoSource</tt> object by all further calls to <tt>FFMS_GetFrame</tt> and <tt>FFMS_GetFrameByTime</tt> until the next call to <tt>FFMS_SetPP</tt> or <tt>FFMS_ResetPP</tt> so that no postprocessing will be applied. Is equivalent to <tt>FFMS_SetPP(VideoSource, NULL, ErrorInfo)</tt> but is more efficient.
@@ -661,6 +663,8 @@ The following public data structures may be of interest.
     int InterlacedFrame;
     int TopFieldFirst;
     char PictType;
+    int ColorSpace;
+    int ColorRange;
 } FFMS_Frame;</pre>
 <p>A struct representing a video frame. The fields are:</p>
 <ul>
@@ -668,13 +672,15 @@ The following public data structures may be of interest.
 <li><b><tt>int Linesize[4]</tt></b> - An array of integers representing the length of each scan line in each of the four picture planes, in bytes. In alternative terminology, this is the "pitch" of the plane. Usually, the total size in bytes of picture plane <tt>i</tt> is <tt>FFMS_Frame->Linesize[i] * FFMS_VideoProperties->Height</tt>, but do note that some pixel formats (most notably YV12) has vertical chroma subsampling, and then the U/V planes may be of a different height than the primary plane.</li>
 <li><b><tt>int EncodedWidth; int EncodedHeight</tt></b> - The original resolution of the frame (in pixels), as encoded in the compressed file, before any scaling was applied. Note that must not necessarily be the same for all frames in a stream.</li>
 <li><b><tt>int EncodedPixelFormat</tt></b> - The original pixel format of the frame, as encoded in the compressed file.</li>
-<li><b><tt>int ScaledWidth; int ScaledHeight;</tt></b> - The output resolution of the frame (in pixels), i.e. the resolution of what is actually stored in the <tt>Data</tt> field. Same as <tt>FFMS_VideoProperties->Width/Height</tt>, but unlike that struct, this one gets updated automatically when you call <tt>FFMS_GetFrame</tt>, so you don't have to call <tt>FFMS_GetVideoProperties</tt> all the time to see if someone changed the output format while you weren't looking.</li>
+<li><b><tt>int ScaledWidth; int ScaledHeight;</tt></b> - The output resolution of the frame (in pixels), i.e. the resolution of what is actually stored in the <tt>Data</tt> field. Same as <tt>FFMS_VideoProperties->Width/Height</tt>, but unlike that struct, this one gets updated automatically when you call <tt>FFMS_GetFrame</tt>, so you don't have to call <tt>FFMS_GetVideoProperties</tt> all the time to see if someone changed the output format while you weren't looking.</li>
 <li><b><tt>int ConvertedPixelFormat</tt></b> - The output pixel format of the frame, i.e. the pixel format of what is actually stored in the <tt>Data</tt> field.</li>
 <li><b><tt>int KeyFrame</tt></b> - Nonzero if the frame is a keyframe, 0 otherwise.</li>
-<li><b><tt>int RepeatPict</tt></b> - An integer repesenting the RFF flag for this frame; i.e. the frame shall be displayed for <tt>1+RepeatPict</tt> time units, where the time units are expressed in the special RFF timebase available in <tt>FFMS_VideoProperties->RFFDenominator</tt> and <tt>FFMS_VideoProperties->RFFNumerator</tt>. Note that if you actually end up using this, you need to ignore the usual timestamps (calculated via the <tt>FFMS_TrackTimeBase</tt> and the frame PTS) since they are fundamentally incompatible with RFF flags.</li>
+<li><b><tt>int RepeatPict</tt></b> - An integer repesenting the RFF flag for this frame; i.e. the frame shall be displayed for <tt>1+RepeatPict</tt> time units, where the time units are expressed in the special RFF timebase available in <tt>FFMS_VideoProperties->RFFDenominator</tt> and <tt>FFMS_VideoProperties->RFFNumerator</tt>. Note that if you actually end up using this, you need to ignore the usual timestamps (calculated via the <tt>FFMS_TrackTimeBase</tt> and the frame PTS) since they are fundamentally incompatible with RFF flags.</li>
 <li><b><tt>int InterlacedFrame</tt></b> - Nonzero if the frame was coded as interlaced, zero otherwise.</li>
 <li><b><tt>int TopFieldFirst</tt></b> - Nonzero if the frame has the top field first, zero if it has the bottom field first. Only relevant if <tt>InterlacedFrame</tt> is nonzero.</li>
 <li><b><tt>char PictType</tt></b> - A single character denoting coding type (I/B/P etc) of the compressed frame. See the Constants and Preprocessor Definitions section for more information about what the different letters mean.</li>
+<li><b><tt>int ColorSpace</tt></b> - Identifies the YUV color coefficients used in the frame. Same as in the MPEG-2 specs; see the <tt>FFMS_ColorSpaces</tt> enum.</li>
+<li><b><tt>int ColorRange</tt></b> - Identifies the luma range of the frame. See the <tt>FFMS_ColorRanges</tt> enum.</li>
 </ul>
 
 <h3>FFMS_TrackTimeBase</h3>
@@ -713,8 +719,8 @@ A struct representing the basic time unit of a track, as a rational number where
     int CropLeft;
     int CropRight;
     int TopFieldFirst;
-    int ColorSpace;
-    int ColorRange;
+    int ColorSpace; <span class="deprecated">[DEPRECATED]</span>
+    int ColorRange; <span class="deprecated">[DEPRECATED]</span>
     double FirstTime;
     double LastTime;
 } FFMS_VideoProperties;</pre>
@@ -726,8 +732,8 @@ A struct representing the basic time unit of a track, as a rational number where
 <li><b><tt>int SARNum; int SARDen;</tt></b> - The sample aspect ratio of the video frames, as a rational number where <tt>SARNum</tt> is the numerator and <tt>SARDen</tt> is the denominator. Note that this is a metadata setting that you are free to ignore, but if you want the proper display aspect ratio with anamorphic material, you should honor it. On the other hand, there are situations (like when encoding) where you should probably ignore it because the user expects it to be ignored.</li>
 <li><b><tt>int CropTop; int CropBottom; int CropLeft; int CropRight;</tt></b> - The number of pixels in each direction you should crop the frame before displaying it. Note that like the SAR, this is a metadata setting and you are free to ignore it, but if you want things to display 100% correctly you should honor it.</li>
 <li><b><tt>int TopFieldFirst</tt></b> - Nonzero if the stream has the top field first, zero if it has the bottom field first.</li>
-<li><b><tt>int ColorSpace</tt></b> - Identifies the YUV color coefficients used in the stream. Same as in the MPEG-2 specs, see AVColorSpace in avcodec.h for more information.</li>
-<li><b><tt>int ColorRange</tt></b> - Identifies the luma range of the stream. 0 means unspecified or unknown, 1 means TV range (16-235) and 2 means PC range (0-255).</li>
+<li><b><tt>int ColorSpace</tt></b> - Identifies the YUV color coefficients used in the stream. Same as in the MPEG-2 specs; see the <tt>FFMS_ColorSpaces</tt> enum. The ColorSpace property in FFMS_Frame should be instead of this, as this can vary between frames.</li>
+<li><b><tt>int ColorRange</tt></b> - Identifies the luma range of the stream. See the <tt>FFMS_ColorRanges</tt> enum. The ColorRange property in FFMS_Frame should be instead of this, as this can vary between frames.</li>
 <li><b><tt>double FirstTime; double LastTime;</tt></b> - The first and last timestamp of the stream respectively, in milliseconds. Useful if you want to know if the stream has a delay, or for quickly determining its length in seconds.</li>
 </ul>
 
@@ -912,7 +918,9 @@ Used for determining the type of a given track. Note that there are currently no
     FFMS_CH_STEREO_RIGHT            = 0x40000000
 };</pre>
 <p>
-Describes various audio channel configurations. The names should be self-explanatory. The actual order if FFmpeg dictated and may vary.
+Describes the audio channel layout of an audio stream. The names should be self-explanatory.<br />
+As you might have noticed, these constants are the same as the ones used for the <tt>dwChannelMask</tt> property of Microsoft's <tt>WAVEFORMATEXTENSIBLE</tt> struct; see <a href="http://msdn.microsoft.com/en-us/library/dd757714%28v=vs.85%29.aspx">its MSDN documentation page</a> for more information.<br />
+The exceptions to this convenient compatibility are <tt>FFMS_CH_STEREO_LEFT</tt> and <tt>FFMS_CH_STEREO_RIGHT</tt>, which are FFmpeg extensions.
 </p>
 
 <h3>FFMS_Resizers</h3>
@@ -943,6 +951,33 @@ Describes various image resizing algorithms, as used in the arguments to <tt>FFM
 Describes the different audio delay handling modes. See <tt>FFMS_CreateAudioSource</tt> for a detailed explanation.
 </p>
 
+<h3>FFMS_ColorSpaces</h3>
+<pre>enum FFMS_ColorSpaces {
+    FFMS_CS_RGB         = 0,
+    FFMS_CS_BT709       = 1,
+    FFMS_CS_UNSPECIFIED = 2,
+    FFMS_CS_FCC         = 4,
+    FFMS_CS_BT470BG     = 5,
+    FFMS_CS_SMPTE170M   = 6,
+    FFMS_CS_SMPTE240M   = 7,
+};</pre>
+<p>
+Identifies the color coefficients used for a YUV stream. The numerical constants are the same as in the MPEG-2 specification.<br />
+Some of these are specified or aliased in a number of places. Most importantly:<br />
+"BT709" (ITU-T Rec. 709) is equivalent to ITU-R BT1361, IEC 61966-2-4 xvYCC709 and SMPTE RP177 Annex B;<br />
+"BT470BG" (ITU-R BT. 470, also known as ITU-T Rec. 601) is equivalent to ITU-R BT601-6 625, ITU-R BT1358 625, ITU-R BT1700 625 PAL & SECAM and IEC 61966-2-4 xvYCC601;<br />
+"SMPTE170M" (SMPTE standard 170 M) is functionally the same as BT470BG, and is furthermore equivalent to ITU-R BT601-6 525, ITU-R BT1358 525, and ITU-R BT1700 NTSC.
+</p>
+
+<h3>FFMS_ColorRanges</h3>
+<pre>enum FFMS_ColorRanges {
+    FFMS_CR_UNSPECIFIED = 0,
+    FFMS_CR_MPEG        = 1,
+    FFMS_CR_JPEG        = 2,
+};</pre>
+<p>
+Identifies the valid range of luma values in a YUV stream. <tt>FFMS_CR_MPEG</tt> is the standard "TV range" with head- and footroom. That is, valid luma values range from 16 to 235 with 8-bit color. <tt>FFMS_CR_JPEG</tt> is "full range"; all representable luma values are valid.
+</p>
 
 
 <h3>FFMS_CC</h3>
diff --git a/doc/ffms2-avisynth.html b/doc/ffms2-avisynth.html
index 35ce47b..111ddca 100644
--- a/doc/ffms2-avisynth.html
+++ b/doc/ffms2-avisynth.html
@@ -169,7 +169,7 @@ FFVideoSource(string source, int track = -1, bool cache = true,
     string cachefile = source + ".ffindex", int fpsnum = -1, int fpsden = 1,
     string pp = "", int threads = -1, string timecodes = "", int seekmode = 1,
     int rffmode = 0, int width = -1, int height = -1, string resizer = "BICUBIC",
-    string colorspace = "", bool utf8 = false)
+    string colorspace = "", bool utf8 = false, string varprefix = "")
 </pre>
 <p>
 Opens video. Will invoke indexing of all video tracks (but no audio tracks) if no valid index file is found.
@@ -192,7 +192,7 @@ Opens video. Will invoke indexing of all video tracks (but no audio tracks) if n
 <dt>int fpsnum = -1, int fpsden = 1</dt>
 <dd>Forces a given (constant) framerate, expressed as a rational number where <tt>fpsnum</tt> is the numerator and <tt>fpsden</tt> is the denominator. Used for VFR to CFR conversion, as it will make <tt>FFVideoSource</tt> drop or duplicate frames to convert VFR to CFR if <tt>fpsnum</tt> is greater than 0. Setting <tt>fpsnum</tt> to a number less than or equal to zero means no frames will be dropped or duplicated.</dd>
 
-<dt>string pp = ""</dt>
+<dt>string pp = "" <span class="deprecated">[DEPRECATED]</span></dt>
 <dd>Sets a chain of postprocessing filters, expressed as a string (see the "PP string format" section below). Mostly useful to do quantizer-based deblocking/deringing, but can also do simple deinterlacing and a few other odd things.</dd>
 
 <dt>int threads = -1</dt>
@@ -234,13 +234,17 @@ Also note that "force film" is mostly useless and only here for completeness' sa
 <dt>bool utf8 = false</dt>
 <dd>Does the same thing as in <tt>FFIndex()</tt>; see that function for details.</dd>
 
+<dt>string varprefix = ""</dt>
+<dd>A string that is added as a prefix to all exported Avisynth variables. This makes it possible to differentiate between variables from different clips. For convenience the last used FFMS function in a script sets the global variable <tt>FFVAR_PREFIX</tt> to its own variable prefix so that <tt>FFInfo()</tt> can default to it.</dd>
+
 </dl>
 
 
 <h3>FFAudioSource</h3>
 <pre>
 FFAudioSource(string source, int track = -1, bool cache = true,
-    string cachefile = source + ".ffindex", int adjustdelay = -1, bool utf8 = false)
+    string cachefile = source + ".ffindex", int adjustdelay = -1, bool utf8 = false,
+	string varprefix = "")
 </pre>
 <p>
 Opens audio. Invokes indexing of all tracks if no valid index file is found, or if the requested track isn't present in the index.
@@ -265,10 +269,10 @@ Opens audio. Invokes indexing of all tracks if no valid index file is found, or
 <pre>
 FFmpegSource2(string source, int vtrack = -1, int atrack = -2, bool cache = true,
     string cachefile = source + ".ffindex", int fpsnum = -1, int fpsden = 1,
-    string pp, int threads = -1, string timecodes = "", int seekmode = 1,
+    string pp = "", int threads = -1, string timecodes = "", int seekmode = 1,
     bool overwrite = false, int width = -1, int height = -1,
     string resizer = "BICUBIC", string colorspace = "", int rffmode = 0,
-    int adjustdelay = -1, bool utf8 = false)
+    int adjustdelay = -1, bool utf8 = false, string varprefix = "")
 </pre>
 <p>A convenience function that combines the functionality of <tt>FFVideoSource</tt> and <tt>FFAudioSource</tt>. The arguments do the same thing as in <tt>FFVideoSource</tt> and <tt>FFAudioSource</tt>; see those functions for details. <tt>vtrack</tt> and <tt>atrack</tt> are the video and audio track to open, respectively; setting <tt>atrack</tt> <= -2 means audio is disabled.</p>
 <p><strong>Note:</strong> this function is provided by <tt>FFMS2.avsi</tt> and is not available unless that script has been imported or autoloaded.</p>
@@ -283,9 +287,10 @@ FFImageSource(string source, int width = -1, int height = -1,
 <p><strong>Note:</strong> this function is provided by <tt>FFMS2.avsi</tt> and is not available unless that script has been imported or autoloaded.</p>
 
 
-<h3>FFPP</h3>
+<h3>FFPP <span class="deprecated">[DEPRECATED]</span></h3>
 <pre>FFPP(clip, string pp)</pre>
 <p>A postprocessing filter. See the <tt>pp</tt> argument to <tt>FFVideoSource</tt> and the "PP string format" section below. In general, using <tt>FFVideoSource</tt>'s <tt>pp</tt> argument instead of this function is recommended (if possible), since if it's used there it has access to video quantizers and can adapt better to the video, particularly when doing deblocking/deringing.</p>
+<p>Postprocessing support is deprecated and will be removed in a future version of FFMS2.</p>
 
 
 <h3>SWScale</h3>
@@ -302,9 +307,10 @@ A helper function used to format a time given in milliseconds into a h:mm:ss.ttt
 
 
 <h3>FFInfo</h3>
-<pre>FFInfo(clip c, bool framenum = true, bool frametype = true, bool cfrtime = true, bool vfrtime = true)</pre>
+<pre>FFInfo(clip c, bool framenum = true, bool frametype = true, bool cfrtime = true,
+	bool vfrtime = true, string varprefix = "")</pre>
 <p>
-A helper function similar to Avisynth's internal <tt>Info()</tt> function; shows general information about the current frame. Note that not all values are exported in all source modes, so some information may not always be shown. The arguments can be used to disable the drawing of certain information if so desired.
+A helper function similar to Avisynth's internal <tt>Info()</tt> function; shows general information about the current frame. Note that not all values are exported in all source modes, so some information may not always be shown. The arguments can be used to disable the drawing of certain information if so desired. Use the varprefix argument to determine which clip you want information about.
 </p>
 <p><strong>Note:</strong> this function is provided by <tt>FFMS2.avsi</tt> and is not available unless that script has been imported or autoloaded.</p>
 
@@ -318,8 +324,14 @@ A helper function similar to Avisynth's internal <tt>Info()</tt> function; shows
 <pre>FFGetLogLevel()</pre>
 <p>Returns the current log level, as an integer.</p>
 
+<h3>FFGetVersion</h3>
+<pre>FFGetVersion()</pre>
+<p>Returns the FFMS2 version, as a string.</p>
+
 
 <h2>Exported Avisynth variables</h2>
+<p>All variable names are prefixed by the <tt>varprefix</tt> argument to the respective <tt>FFVideoSource</tt> or <tt>FFAudioSource</tt> call that generated them.</p>
+
 <dl>
 <dt>FFSAR_NUM, FFSAR_DEN, FFSAR</dt>
 <dd>
@@ -359,8 +371,15 @@ b: FF_BI_TYPE (no good explanation available)
 
 <dt>FFVFR_TIME</dt>
 <dd>The actual time of the source frame in milliseconds. Only set when no type of CFR conversion is being done (<tt>rffmode</tt> and <tt>fpsnum</tt> left at their defaults).</dd>
-</dl>
 
+
+<dt>FFCHANNEL_LAYOUT</dt>
+<dd>The audio channel layout of the audio stream. This is exported as a very cryptic integer that is constructed in the same way as the <tt>dwChannelMask</tt> property of the Windows <tt>WAVEFORMATEXTENSIBLE</tt> struct. If you don't know what the <tt>WAVEFORMATEXTENSIBLE</tt> is or what the <tt>dwChannelMask</tt> does, don't worry about it.</dd>
+
+<dt>FFVAR_PREFIX</dt>
+<dd>The variable prefix of the last called FFMS source function. Note that this is a global variable</dd>
+
+</dl>
 </div>
 
 
diff --git a/doc/ffms2-changelog.html b/doc/ffms2-changelog.html
index 154c97d..b91f28f 100644
--- a/doc/ffms2-changelog.html
+++ b/doc/ffms2-changelog.html
@@ -11,12 +11,32 @@ FFmpegSource2 Changelog
 <div class="maincontent">
 <h1>FFmpegSource2 Changelog</h1>
 <ul>
+<li>2.17<ul>
+<li>Reworked color matrix and color range handling a bit, which fixed a bug that could cause FFMS2 to always output TV range even if the input was full range. (TheFluff)</li>
+<li>The autotools build system can now create debug builds properly. (Daemon404)</li>
+<li>Deprecated parts of the API will now cause compiler warnings when you use them. (TheFluff)</li>
+<li>Added a <tt>FFMS_GetVersion</tt> function to the API (lets library users get the version number at runtime) and exposed it in Avisynth as <tt>FFGetVersion</tt>. (TheRyuu, TheFluff)</li>
+<li>Added a variable prefix option to the Avisynth functions. Its primary purpose is to get subsequent calls to source functions from overwriting variables from earlier calls. (TheFluff)</li>
+<li>Make it possible to open single-frame videos without explicitly setting seekmode to -1 for you weird people who want to open images with ffms (Plorkyeran)</li>
+<li>Fixed bug where indices would sometimes be incorrectly considered valid (TheRyuu)</li>
+<li>Add support for recent versions of Libav/FFmpeg built as shared libraries (Plorkyeran, TheRyuu, Kovensky)</li>
+<li>When possible, non-API symbols are no longer exported (Daemon404, TheFluff)</li>
+<li>Deprecate postprocessing support. Libav and FFmpeg are planning on removing it at some point in the near future and it's really not very useful.</li>
+<li>Fix the pkg-config version on OS X (Plorkyeran).</li>
+<li>Fixed a bug that could cause the <tt>FFmpegSource2()</tt> Avisynth function to not use UTF8 filenames even when told to do so. (pandv2)</li>
+<li>Fixed a few minor memory leaks. (Plorkyeran)</li>
+<li>Adjusting audio delay relative to the first video track should now work properly again (was broken in 2.16). (Plorkyeran)</li>
+<li>General bitrot fixes to deal with changes in Libav/FFmpeg (everyone)</li>
+<li>Corrected handling of codec private data when using a non-libavformat parser. Fixes decoding of FFV1 and UTVideo in MKV, among other things. (TheFluff)</li>
+<li>Bump minimum required version of FFmpeg to 0.6.</li>
+</ul>
+</li>
 <li>2.16<ul>
-<li>Reimplemented output colorspace selection, this should fix all issues with the avisynth plugin when opening yuv420p10 or yuv444 material plus several other less common cases. (Myrsloik)</li>
-<li>Added FFMS_SetOutputFormatV2 to the API. This function allows you to specify PixelFormats >= 64 for use as output. (Myrsloik)</li>
-<li>Fixed a serious bug that could cause crashes and completely useless index files with h264 in matroska. (Myrsloik)</li>
-<li>Automatically detect number of decoding threads.  The avisynth video source funtion already did this, now moved so the api can use it as well. (TheRyuu)</li> 
-<li>Re-add the ability to target x64 with msvc since it's a bit more sane now. (TheRyuu)</li>
+<li>Reimplemented output colorspace selection, this should fix all issues with the Avisynth plugin when opening yuv420p10 or yuv444 material plus several other less common cases. (Myrsloik)</li>
+<li>Added <tt>FFMS_SetOutputFormatV2</tt> to the API. This function allows you to specify PixelFormats >= 64 for use as output. (Myrsloik)</li>
+<li>Fixed a serious bug that could cause crashes and completely useless index files with h264 in Matroska. (Myrsloik)</li>
+<li>Automatically detect number of decoding threads.  The Avisynth video source funtion already did this, now moved so the API can use it as well. (TheRyuu)</li> 
+<li>Re-add the ability to target x64 with MSVC, since it's a bit more sane now. (TheRyuu)</li>
 <li>Fixed a bug that could cause crashes when reading audio if FFMS2 was compiled with GCC. (Myrsloik)</li>
 <li>ffmsindex will no longer crash if it cannot open the file given to it for indexing. (TheFluff)</li>
 <li>FFMS2 will no longer crash if the video decoder feeds it an empty frame (can sometimes happen when using lots of decoder threads); you'll get a nice error message instead. (TheFluff)</li>
diff --git a/doc/style.css b/doc/style.css
index cac940b..7b925d6 100644
--- a/doc/style.css
+++ b/doc/style.css
@@ -30,12 +30,15 @@ a:visited {
 	color: #103020;
 }
 h1, h2, h3 {
-	margin: 1.2em 0em -0.2em; 
+	margin: 1.2em 0em -0.2em;
 }
 h4 {
 	margin: 0em 0em -0.5em;
 	text-decoration: underline;
 }
+.deprecated {
+	color: red;
+}
 img {
 	border-width: 0px;
 }
@@ -53,4 +56,5 @@ body div.maincontent {
 .avisynth-functionref dt {
 	font-family: monospace;
 	padding: 5px 3px 3px 3px;
-}
\ No newline at end of file
+}
+
diff --git a/etc/FFMS2.avsi b/etc/FFMS2.avsi
index 6035667..230f389 100644
--- a/etc/FFMS2.avsi
+++ b/etc/FFMS2.avsi
@@ -5,7 +5,7 @@ function FFmpegSource2(string source, int "vtrack", int "atrack", bool "cache",
 	string "cachefile", int "fpsnum", int "fpsden", string "pp", int "threads", \
 	string "timecodes", int "seekmode", bool "overwrite", int "width", int "height", \
 	string "resizer", string "colorspace", int "rffmode", int "adjustdelay", \
-	bool "utf8") {
+	bool "utf8", string "varprefix") {
 	
 	vtrack 		= default(vtrack,-1)
 	atrack		= default(atrack,-2)
@@ -25,31 +25,36 @@ function FFmpegSource2(string source, int "vtrack", int "atrack", bool "cache",
 	rffmode		= default(rffmode,0)
 	adjustdelay	= default(adjustdelay,-1)
 	utf8		= default(utf8,false)
+	varprefix	= default(varprefix, "")
 	
 	((cache == true) && (atrack <= -2)) ? ffindex(source=source, cachefile=cachefile, \
-		indexmask=0, overwrite=overwrite) : (cache == true) ? ffindex(source=source, \
+		indexmask=0, overwrite=overwrite, utf8=utf8) : (cache == true) ? ffindex(source=source, \
 		cachefile=cachefile, indexmask=-1, overwrite=overwrite, utf8=utf8) : nop
 	
 	v = ffvideosource(source=source, track=vtrack, cache=cache, cachefile=cachefile, \
 		fpsnum=fpsnum, fpsden=fpsden, pp=pp, threads=threads, timecodes=timecodes, \
 		seekmode=seekmode, rffmode=rffmode, width=width, height=height, resizer=resizer, \
-		colorspace=colorspace, utf8=utf8)
+		colorspace=colorspace, utf8=utf8, varprefix=varprefix)
 	
 	a = (atrack <= -2) ? blankclip(audio_rate=0) : ffaudiosource(source=source, \
-		track=atrack, cache=cache, cachefile=cachefile, adjustdelay=adjustdelay, utf8=utf8)
+		track=atrack, cache=cache, cachefile=cachefile, adjustdelay=adjustdelay, \
+		utf8=utf8, varprefix=varprefix)
 	
 	return audiodubex(v,a)
 }
 
-function FFImageSource(string source, int "width", int "height", string "resizer", string "colorspace", bool "utf8") {
+function FFImageSource(string source, int "width", int "height", string "resizer", \
+	string "colorspace", bool "utf8", string "varprefix") {
 
 	width		= default(width,-1)
 	height		= default(height,-1)
 	resizer		= default(resizer,"BICUBIC")
 	colorspace	= default(colorspace,"")
 	utf8		= default(utf8,false)
+	varprefix	= default(varprefix,"")
 
-	return FFVideoSource(source, cache=false, seekmode=-1, width=width, height=height, resizer=resizer, colorspace=colorspace, utf8=utf8)
+	return FFVideoSource(source, cache=false, seekmode=-1, width=width, height=height, \
+		resizer=resizer, colorspace=colorspace, utf8=utf8, varprefix=varprefix)
 }
 
 function FFCopyrightInfringement(string source) {
@@ -79,20 +84,23 @@ function FFFormatTime(int ms) {
 	return string(h) + ":" + string(m,"%02.0f") + ":" + string(s,"%02.0f") + "." + string(ms,"%03.0f")
 }
 
-function FFInfo(clip c, bool "framenum", bool "frametype", bool "cfrtime", bool "vfrtime") {
+function FFInfo(clip c, bool "framenum", bool "frametype", bool "cfrtime", bool "vfrtime", string "varprefix") {
 
 	framenum	= default(framenum,true)
 	frametype	= default(frametype,true)
 	cfrtime		= default(cfrtime,true)
 	vfrtime		= default(vfrtime,true)
+	varprefix	= default(varprefix, FFVAR_PREFIX)
 
-	c.frameevaluate(""" fftempstring = "" """)
+	c.frameevaluate("""
+		fftempstring = "" 
+		varprefix = """" + varprefix + """"""")
 
 	framenum ? frameevaluate("""fftempstring = fftempstring + "Frame Number: " + string(current_frame) + " of " + string(framecount()) + "\n" """, after_frame=true) : nop()
-	frametype ? frameevaluate("""fftempstring = fftempstring + "Picture Type: " + chr(FFPICT_TYPE) + "\n" """, after_frame=true) : nop()
+	frametype ? frameevaluate("""fftempstring = fftempstring + "Picture Type: " + chr(eval(varprefix + "FFPICT_TYPE")) + "\n" """, after_frame=true) : nop()
 
 	cfrtime ? frameevaluate("""fftempstring = fftempstring + "CFR Time: " + FFFormatTime(round((current_frame * 1000) / framerate())) + "\n" """, after_frame=true) : nop()
-	vfrtime ? frameevaluate("""fftempstring = fftempstring + "VFR Time: " + FFFormatTime(FFVFR_TIME) + "\n" """, after_frame=true) : nop()
+	vfrtime ? frameevaluate("""fftempstring = fftempstring + "VFR Time: " + FFFormatTime(eval(varprefix + "FFVFR_TIME")) + "\n" """, after_frame=true) : nop()
 
 	return scriptclip("subtitle(fftempstring, lsp = 1)", after_frame=true)
 }
\ No newline at end of file
diff --git a/ffms2.pc.in b/ffms2.pc.in
index 27aaac9..7e316ea 100644
--- a/ffms2.pc.in
+++ b/ffms2.pc.in
@@ -7,7 +7,8 @@ includedir=@includedir@
 
 Name: ffms2
 Description: The Fabulous FM Library 2
-Requires: libavformat libavcodec libswscale libavutil @postproc@
+Requires.private: libavformat libavcodec libswscale libavutil
 Version: @FFMS_VERSION@
-Libs: -L${libdir} -lffms2 @ZLIB_CPPFLAGS@ -lz
+Libs.private: @ZLIB_LDFLAGS@ -lz
+Libs: -L${libdir} -lffms2
 Cflags: -I${includedir}
diff --git a/include/ffms.h b/include/ffms.h
index 85b49ac..4a58470 100644
--- a/include/ffms.h
+++ b/include/ffms.h
@@ -22,32 +22,64 @@
 #define FFMS_H
 
 // Version format: major - minor - micro - bump
-#define FFMS_VERSION ((2 << 24) | (16 << 16) | (0 << 8) | 0)
+#define FFMS_VERSION ((2 << 24) | (17 << 16) | (0 << 8) | 0)
 
 #include <stdint.h>
 
-#ifdef __cplusplus
+
+/********
+*	The following preprocessor voodoo ensures that all API symbols are exported
+*	as intended on all supported platforms, that non-API symbols are hidden (where possible),
+*	and that the correct calling convention and extern declarations are used.
+*	The end result should be that linking to FFMS2 Just Works.
+********/
+
+// Convenience for C++ users.
+#if defined(__cplusplus)
 #	define FFMS_EXTERN_C extern "C"
 #else
 #	define FFMS_EXTERN_C
 #endif
 
-#ifdef _WIN32
+// On win32, we need to ensure we use stdcall with all compilers.
+#if defined(_WIN32)
 #	define FFMS_CC __stdcall
-#	ifdef _MSC_VER
-#		ifdef FFMS_EXPORTS
-#			define FFMS_API(ret) FFMS_EXTERN_C __declspec(dllexport) ret FFMS_CC
-#		else
-#			define FFMS_API(ret) FFMS_EXTERN_C __declspec(dllimport) ret FFMS_CC
-#		endif
-#	else
-#		define FFMS_API(ret) FFMS_EXTERN_C ret FFMS_CC
-#	endif
 #else
 #	define FFMS_CC
-#	define FFMS_API(ret) FFMS_EXTERN_C ret FFMS_CC
 #endif
 
+// compiler-specific deprecation attributes
+#if defined(__GNUC__) && (__GNUC__ >= 4)
+#	define FFMS_DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER)
+#	define FFMS_DEPRECATED __declspec(deprecated)
+#else
+#	define FFMS_DEPRECATED
+#endif
+
+
+// And now for some symbol hide-and-seek...
+#if defined(_MSC_VER) // MSVC
+#	if defined(FFMS_EXPORTS) // building the FFMS2 library itself, with visible API symbols
+#		define FFMS_API(ret) FFMS_EXTERN_C __declspec(dllexport) ret FFMS_CC
+#		define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED __declspec(dllexport) ret FFMS_CC
+#	else // building something that depends on FFMS2
+#		define FFMS_API(ret) FFMS_EXTERN_C __declspec(dllimport) ret FFMS_CC
+#		define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED __declspec(dllimport) ret FFMS_CC
+#	endif // defined(FFMS_EXPORTS)
+// GCC 4 or later: export API symbols only. Some GCC 3.x versions support the visibility attribute too,
+// but we don't really care enough about that to add compatibility defines for it.
+#elif defined(__GNUC__) && __GNUC__ >= 4
+#	define FFMS_API(ret) FFMS_EXTERN_C __attribute__((visibility("default"))) ret FFMS_CC
+#	define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED __attribute__((visibility("default"))) ret FFMS_CC
+#else // fallback for everything else
+#	define FFMS_API(ret) FFMS_EXTERN_C ret FFMS_CC
+#	define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED ret FFMS_CC
+#endif // defined(_MSC_VER)
+
+
+// we now return you to your regularly scheduled programming.
+
 typedef struct FFMS_ErrorInfo {
 	int ErrorType;
 	int SubType;
@@ -184,6 +216,22 @@ enum FFMS_AudioDelayModes {
 	FFMS_DELAY_FIRST_VIDEO_TRACK	= -1
 };
 
+enum FFMS_ColorSpaces {
+	FFMS_CS_RGB			= 0,
+	FFMS_CS_BT709		= 1,
+	FFMS_CS_UNSPECIFIED	= 2,
+	FFMS_CS_FCC			= 4,
+	FFMS_CS_BT470BG		= 5,
+	FFMS_CS_SMPTE170M	= 6,
+	FFMS_CS_SMPTE240M	= 7,
+};
+
+enum FFMS_ColorRanges {
+	FFMS_CR_UNSPECIFIED = 0,
+	FFMS_CR_MPEG		= 1, // 219*2^(n-8), i.e. 16-235 with 8-bit samples
+	FFMS_CR_JPEG		= 2, // 2^n-1, or "fullrange"
+};
+
 typedef struct FFMS_Frame {
 	uint8_t *Data[4];
 	int Linesize[4];
@@ -198,6 +246,8 @@ typedef struct FFMS_Frame {
 	int InterlacedFrame;
 	int TopFieldFirst;
 	char PictType;
+	int ColorSpace;
+	int ColorRange;
 } FFMS_Frame;
 
 typedef struct FFMS_TrackTimeBase {
@@ -224,8 +274,8 @@ typedef struct FFMS_VideoProperties {
 	int CropLeft;
 	int CropRight;
 	int TopFieldFirst;
-	int ColorSpace; // same as in the MPEG-2 specs, see AVColorSpace in avcodec.h
-	int ColorRange; // 0=unspecified, 1=16-235, 2=0-255
+	FFMS_DEPRECATED int ColorSpace;
+	FFMS_DEPRECATED int ColorRange;
 	double FirstTime;
 	double LastTime;
 } FFMS_VideoProperties;
@@ -235,7 +285,7 @@ typedef struct FFMS_AudioProperties {
 	int SampleRate;
 	int BitsPerSample;
 	int Channels;
-	int64_t ChannelLayout;
+	int64_t ChannelLayout; // should probably be a plain int, none of the constants are >32 bits long
 	int64_t NumSamples;
 	double FirstTime;
 	double LastTime;
@@ -259,11 +309,11 @@ FFMS_API(const FFMS_AudioProperties *) FFMS_GetAudioProperties(FFMS_AudioSource
 FFMS_API(const FFMS_Frame *) FFMS_GetFrame(FFMS_VideoSource *V, int n, FFMS_ErrorInfo *ErrorInfo);
 FFMS_API(const FFMS_Frame *) FFMS_GetFrameByTime(FFMS_VideoSource *V, double Time, FFMS_ErrorInfo *ErrorInfo);
 FFMS_API(int) FFMS_GetAudio(FFMS_AudioSource *A, void *Buf, int64_t Start, int64_t Count, FFMS_ErrorInfo *ErrorInfo);
-FFMS_API(int) /*DEPRECATED*/ FFMS_SetOutputFormatV(FFMS_VideoSource *V, int64_t TargetFormats, int Width, int Height, int Resizer, FFMS_ErrorInfo *ErrorInfo);
+FFMS_DEPRECATED_API(int) FFMS_SetOutputFormatV(FFMS_VideoSource *V, int64_t TargetFormats, int Width, int Height, int Resizer, FFMS_ErrorInfo *ErrorInfo);
 FFMS_API(int) FFMS_SetOutputFormatV2(FFMS_VideoSource *V, const int *TargetFormats, int Width, int Height, int Resizer, FFMS_ErrorInfo *ErrorInfo); /* Introduced in FFMS_VERSION ((2 << 24) | (15 << 16) | (3 << 8) | 0) */
 FFMS_API(void) FFMS_ResetOutputFormatV(FFMS_VideoSource *V);
-FFMS_API(int) FFMS_SetPP(FFMS_VideoSource *V, const char *PP, FFMS_ErrorInfo *ErrorInfo);
-FFMS_API(void) FFMS_ResetPP(FFMS_VideoSource *V);
+FFMS_DEPRECATED_API(int) FFMS_SetPP(FFMS_VideoSource *V, const char *PP, FFMS_ErrorInfo *ErrorInfo);
+FFMS_DEPRECATED_API(void) FFMS_ResetPP(FFMS_VideoSource *V);
 FFMS_API(void) FFMS_DestroyIndex(FFMS_Index *Index);
 FFMS_API(int) FFMS_GetSourceType(FFMS_Index *Index);
 FFMS_API(int) FFMS_GetSourceTypeI(FFMS_Indexer *Indexer);
diff --git a/include/ffmscompat.h b/include/ffmscompat.h
index 1e77459..1a789d5 100644
--- a/include/ffmscompat.h
+++ b/include/ffmscompat.h
@@ -21,6 +21,24 @@
 #ifndef FFMSCOMPAT_H
 #define	FFMSCOMPAT_H
 
+// Defaults to libav compatibility, uncomment (when building with msvc) to force ffmpeg compatibility.
+//#define FFMS_USE_FFMPEG_COMPAT
+
+// Attempt to auto-detect whether or not we are using ffmpeg.  Newer versions of ffmpeg have their micro versions 100+
+#if LIBAVFORMAT_VERSION_MICRO > 99 || LIBAVUTIL_VERSION_MICRO > 99 || LIBAVCODEC_VERSION_MICRO > 99 || LIBSWSCALE_VERSION_MICRO > 99
+#	ifndef FFMS_USE_FFMPEG_COMPAT
+#		define FFMS_USE_FFMPEG_COMPAT
+#	endif
+#endif
+
+// Helper to handle checking for different versions in libav and ffmpeg
+// First version is required libav versio, second is required ffmpeg version
+#ifdef FFMS_USE_FFMPEG_COMPAT
+#  define VERSION_CHECK(LIB, cmp, u1, u2, u3, major, minor, micro) ((LIB) cmp (AV_VERSION_INT(major, minor, micro)))
+#else
+#  define VERSION_CHECK(LIB, cmp, major, minor, micro, u1, u2, u3) ((LIB) cmp (AV_VERSION_INT(major, minor, micro)))
+#endif
+
 #ifdef _WIN32
 #	define snprintf _snprintf
 #	ifdef __MINGW32__
@@ -40,6 +58,9 @@
 #	if (LIBAVFORMAT_VERSION_INT) < (AV_VERSION_INT(53,3,0))
 #		define avformat_find_stream_info(c,o) av_find_stream_info(c)
 #	endif
+#	if VERSION_CHECK(LIBAVFORMAT_VERSION_INT, <, 53, 17, 0, 53, 25, 0)
+#		define avformat_close_input(c) av_close_input_file(*c)
+#	endif
 #endif
 
 #ifdef LIBAVCODEC_VERSION_INT
@@ -58,12 +79,20 @@
 #		define avcodec_open2(a,c,o) avcodec_open(a,c)
 #		define avcodec_alloc_context3(c) avcodec_alloc_context()
 #	endif
+#	if VERSION_CHECK(LIBAVCODEC_VERSION_INT, <, 53, 22, 0, 53, 31, 0)
+#		define FFMS_CALCULATE_DELAY (CodecContext->has_b_frames)
+#	else
+#		define FFMS_CALCULATE_DELAY (CodecContext->has_b_frames + (CodecContext->thread_count - 1))
+#	endif
 #endif
 
 #ifdef LIBAVUTIL_VERSION_INT
 #	if (LIBAVUTIL_VERSION_INT) < (AV_VERSION_INT(51, 1, 0))
 #		define av_get_picture_type_char av_get_pict_type_char
 #	endif
+#	if (LIBAVUTIL_VERSION_INT) < (AV_VERSION_INT(51, 2, 0))
+#		define av_get_pix_fmt_name avcodec_get_pix_fmt_name
+#	endif
 #endif
 
 #endif // FFMSCOMPAT_H
diff --git a/ltmain.sh b/ltmain.sh
index 3061e3c..6dfcfd5 100755
--- a/ltmain.sh
+++ b/ltmain.sh
@@ -1374,6 +1374,21 @@ func_replace_sysroot ()
 func_infer_tag ()
 {
     $opt_debug
+
+    # FreeBSD-specific: where we install compilers with non-standard names
+    tag_compilers_CC="*cc cc* *gcc gcc* clang"
+    tag_compilers_CXX="*c++ c++* *g++ g++* clang++"
+    base_compiler=`set -- "$@"; echo $1`
+
+    # If $tagname isn't set, then try to infer if the default "CC" tag applies
+    if test -z "$tagname"; then
+      for zp in $tag_compilers_CC; do
+        case $base_compiler in
+	 $zp) tagname="CC"; break;;
+	esac
+      done
+    fi
+
     if test -n "$available_tags" && test -z "$tagname"; then
       CC_quoted=
       for arg in $CC; do
@@ -1410,7 +1425,22 @@ func_infer_tag ()
 	      break
 	      ;;
 	    esac
-	  fi
+
+	    # FreeBSD-specific: try compilers based on inferred tag
+	    if test -z "$tagname"; then
+	      eval "tag_compilers=\$tag_compilers_${z}"
+	      if test -n "$tag_compilers"; then
+		for zp in $tag_compilers; do
+		  case $base_compiler in   
+		    $zp) tagname=$z; break;;
+		  esac
+		done
+		if test -n "$tagname"; then
+		  break
+		fi
+	      fi
+            fi
+          fi
 	done
 	# If $tagname still isn't set, then no tagged configuration
 	# was found and let the user know that the "--tag" command
@@ -3514,6 +3544,9 @@ static const void *lt_preloaded_setup() {
 	  ;;
 	esac
 	;;
+      *-*-freebsd*)
+	# FreeBSD doesn't need this...
+	;;
       *)
 	func_fatal_error "unknown suffix for \`$my_dlsyms'"
 	;;
@@ -5583,6 +5616,7 @@ func_mode_link ()
 	  esac
 	  ;;
 	esac
+	deplibs="$deplibs $arg"
 	continue
 	;;
 
@@ -6153,13 +6187,30 @@ func_mode_link ()
 	    finalize_deplibs="$deplib $finalize_deplibs"
 	  else
 	    func_append compiler_flags " $deplib"
-	    if test "$linkmode" = lib ; then
-		case "$new_inherited_linker_flags " in
-		    *" $deplib "*) ;;
-		    * ) func_append new_inherited_linker_flags " $deplib" ;;
-		esac
-	    fi
 	  fi
+
+	  case $linkmode in
+	  lib)
+	    deplibs="$deplib $deplibs"
+	    test "$pass" = conv && continue
+	    newdependency_libs="$deplib $newdependency_libs"
+	    ;;
+	  prog)
+	    if test "$pass" = conv; then
+	      deplibs="$deplib $deplibs"
+	      continue
+	    fi
+	    if test "$pass" = scan; then
+	      deplibs="$deplib $deplibs"
+	    else
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    fi
+	    ;;
+	  *)
+	    ;;
+	  esac # linkmode
+
 	  continue
 	  ;;
 	-l*)
diff --git a/m4/libtool.m4 b/m4/libtool.m4
index d812584..8240475 100644
--- a/m4/libtool.m4
+++ b/m4/libtool.m4
@@ -2406,10 +2406,6 @@ dgux*)
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
-freebsd1*)
-  dynamic_linker=no
-  ;;
-
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
@@ -2417,7 +2413,7 @@ freebsd* | dragonfly*)
     objformat=`/usr/bin/objformat`
   else
     case $host_os in
-    freebsd[[123]]*) objformat=aout ;;
+    freebsd[[23]].*) objformat=aout ;;
     *) objformat=elf ;;
     esac
   fi
@@ -2435,7 +2431,7 @@ freebsd* | dragonfly*)
   esac
   shlibpath_var=LD_LIBRARY_PATH
   case $host_os in
-  freebsd2*)
+  freebsd2.*)
     shlibpath_overrides_runpath=yes
     ;;
   freebsd3.[[01]]* | freebsdelf3.[[01]]*)
@@ -5110,10 +5106,6 @@ _LT_EOF
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
       ;;
 
-    freebsd1*)
-      _LT_TAGVAR(ld_shlibs, $1)=no
-      ;;
-
     # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
     # support.  Future versions do this automatically, but an explicit c++rt0.o
     # does not break anything, and helps significantly (at the cost of a little
@@ -5126,7 +5118,7 @@ _LT_EOF
       ;;
 
     # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
+    freebsd2.*)
       _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
       _LT_TAGVAR(hardcode_direct, $1)=yes
       _LT_TAGVAR(hardcode_minus_L, $1)=yes
@@ -6137,7 +6129,7 @@ if test "$_lt_caught_CXX_error" != yes; then
         esac
         ;;
 
-      freebsd[[12]]*)
+      freebsd2.*)
         # C++ shared libraries reported to be fairly broken before
 	# switch to ELF
         _LT_TAGVAR(ld_shlibs, $1)=no
diff --git a/src/avisynth/avisynth.cpp b/src/avisynth/avisynth.cpp
index 6b41daf..aad5edd 100644
--- a/src/avisynth/avisynth.cpp
+++ b/src/avisynth/avisynth.cpp
@@ -68,8 +68,8 @@ static AVSValue __cdecl CreateFFIndex(AVSValue Args, void* UserData, IScriptEnvi
 	else
 		Env->ThrowError("FFIndex: Invalid demuxer requested");
 
-	FFMS_Index *Index = NULL;
-	if (OverWrite || !(Index = FFMS_ReadIndex(CacheFile, &E))) {
+	FFMS_Index *Index = FFMS_ReadIndex(CacheFile, &E);
+	if (OverWrite || !Index || (Index && FFMS_IndexBelongsToFile(Index, Source, 0) != FFMS_ERROR_SUCCESS)) {
 		FFMS_Indexer *Indexer = FFMS_CreateIndexerWithDemuxer(Source, Demuxer, &E);
 		if (!Indexer)
 			Env->ThrowError("FFIndex: %s", E.Buffer);
@@ -116,6 +116,7 @@ static AVSValue __cdecl CreateFFVideoSource(AVSValue Args, void* UserData, IScri
 	int Height = Args[12].AsInt(0);
 	const char *Resizer = Args[13].AsString("BICUBIC");
 	const char *ColorSpace = Args[14].AsString("");
+	const char *VarPrefix = Args[16].AsString("");
 
 	if (FPSDen < 1)
 		Env->ThrowError("FFVideoSource: FPS denominator needs to be 1 or higher");
@@ -186,7 +187,7 @@ static AVSValue __cdecl CreateFFVideoSource(AVSValue Args, void* UserData, IScri
 	AvisynthVideoSource *Filter;
 
 	try {
-		Filter = new AvisynthVideoSource(Source, Track, Index, FPSNum, FPSDen, PP, Threads, SeekMode, RFFMode, Width, Height, Resizer, ColorSpace, Env);
+		Filter = new AvisynthVideoSource(Source, Track, Index, FPSNum, FPSDen, PP, Threads, SeekMode, RFFMode, Width, Height, Resizer, ColorSpace, VarPrefix, Env);
 	} catch (...) {
 		FFMS_DestroyIndex(Index);
 		throw;
@@ -212,6 +213,7 @@ static AVSValue __cdecl CreateFFAudioSource(AVSValue Args, void* UserData, IScri
 	bool Cache = Args[2].AsBool(true);
 	const char *CacheFile = Args[3].AsString("");
 	int AdjustDelay = Args[4].AsInt(-1);
+	const char *VarPrefix = Args[6].AsString("");
 
 	if (Track <= -2)
 		Env->ThrowError("FFAudioSource: No audio track selected");
@@ -282,7 +284,7 @@ static AVSValue __cdecl CreateFFAudioSource(AVSValue Args, void* UserData, IScri
 	AvisynthAudioSource *Filter;
 
 	try {
-		Filter = new AvisynthAudioSource(Source, Track, Index, AdjustDelay, Env);
+		Filter = new AvisynthAudioSource(Source, Track, Index, AdjustDelay, VarPrefix, Env);
 	} catch (...) {
 		FFMS_DestroyIndex(Index);	
 		throw;
@@ -312,13 +314,14 @@ static AVSValue __cdecl FFSetLogLevel(AVSValue Args, void* UserData, IScriptEnvi
 }
 
 static AVSValue __cdecl FFGetVersion(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
-	return FFMS_GetVersion();
+	int Version = FFMS_GetVersion();
+	return Env->Sprintf("%d.%d.%d.%d", Version >> 24, (Version & 0xFF0000) >> 16, (Version & 0xFF00) >> 8, Version & 0xFF);
 }
 
 extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit2(IScriptEnvironment* Env) {
     Env->AddFunction("FFIndex", "[source]s[cachefile]s[indexmask]i[dumpmask]i[audiofile]s[errorhandling]i[overwrite]b[utf8]b[demuxer]s", CreateFFIndex, 0);
-	Env->AddFunction("FFVideoSource", "[source]s[track]i[cache]b[cachefile]s[fpsnum]i[fpsden]i[pp]s[threads]i[timecodes]s[seekmode]i[rffmode]i[width]i[height]i[resizer]s[colorspace]s[utf8]b", CreateFFVideoSource, 0);
-    Env->AddFunction("FFAudioSource", "[source]s[track]i[cache]b[cachefile]s[adjustdelay]i[utf8]b", CreateFFAudioSource, 0);
+	Env->AddFunction("FFVideoSource", "[source]s[track]i[cache]b[cachefile]s[fpsnum]i[fpsden]i[pp]s[threads]i[timecodes]s[seekmode]i[rffmode]i[width]i[height]i[resizer]s[colorspace]s[utf8]b[varprefix]s", CreateFFVideoSource, 0);
+	Env->AddFunction("FFAudioSource", "[source]s[track]i[cache]b[cachefile]s[adjustdelay]i[utf8]b[varprefix]s", CreateFFAudioSource, 0);
 #ifdef FFMS_USE_POSTPROC
 	Env->AddFunction("FFPP", "c[pp]s", CreateFFPP, 0);
 #endif // FFMS_USE_POSTPROC
diff --git a/src/avisynth/avssources.cpp b/src/avisynth/avssources.cpp
index 2b17d65..581730b 100644
--- a/src/avisynth/avssources.cpp
+++ b/src/avisynth/avssources.cpp
@@ -27,12 +27,13 @@
 AvisynthVideoSource::AvisynthVideoSource(const char *SourceFile, int Track, FFMS_Index *Index,
 		int FPSNum, int FPSDen, const char *PP, int Threads, int SeekMode, int RFFMode,
 		int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
-		const char *ConvertToFormatName, IScriptEnvironment* Env) {
+		const char *ConvertToFormatName, const char *VarPrefix, IScriptEnvironment* Env) {
 
 	memset(&VI, 0, sizeof(VI));
 	this->FPSNum = FPSNum;
 	this->FPSDen = FPSDen;
 	this->RFFMode = RFFMode;
+	this->VarPrefix = VarPrefix;
 
 	char ErrorMsg[1024];
 	FFMS_ErrorInfo E;
@@ -159,20 +160,18 @@ AvisynthVideoSource::AvisynthVideoSource(const char *SourceFile, int Track, FFMS
 	}
 
 	// Set AR variables
-	Env->SetVar("FFSAR_NUM", VP->SARNum);
-	Env->SetVar("FFSAR_DEN", VP->SARDen);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFSAR_NUM"), VP->SARNum);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFSAR_DEN"), VP->SARDen);
 	if (VP->SARNum > 0 && VP->SARDen > 0)
-		Env->SetVar("FFSAR", VP->SARNum / (double)VP->SARDen);
+		Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFSAR"), VP->SARNum / (double)VP->SARDen);
 
 	// Set crop variables
-	Env->SetVar("FFCROP_LEFT", VP->CropLeft);
-	Env->SetVar("FFCROP_RIGHT", VP->CropRight);
-	Env->SetVar("FFCROP_TOP", VP->CropTop);
-	Env->SetVar("FFCROP_BOTTOM", VP->CropBottom);
-
-	// Set color information
-	Env->SetVar("FFCOLOR_SPACE", VP->ColorSpace);
-	Env->SetVar("FFCOLOR_RANGE", VP->ColorRange);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_LEFT"), VP->CropLeft);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_RIGHT"), VP->CropRight);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_TOP"), VP->CropTop);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_BOTTOM"), VP->CropBottom);
+
+	Env->SetGlobalVar("FFVAR_PREFIX", this->VarPrefix);
 }
 
 AvisynthVideoSource::~AvisynthVideoSource() {
@@ -250,6 +249,10 @@ void AvisynthVideoSource::InitOutputFormat(
 
 	if (RFFMode > 0 && 	TargetPixelFormat != PIX_FMT_NV12)
 		Env->ThrowError("FFVideoSource: Only the default output colorspace can be used in RFF mode");
+	
+	// set color information variables
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCOLOR_SPACE"), F->ColorSpace);
+	Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCOLOR_RANGE"), F->ColorRange);
 
 	if (VP->TopFieldFirst)
 		VI.image_type = VideoInfo::IT_TFF;
@@ -346,13 +349,13 @@ PVideoFrame AvisynthVideoSource::GetFrame(int n, IScriptEnvironment *Env) {
 			Frame = FFMS_GetFrame(V, n, &E);
 			FFMS_Track *T = FFMS_GetTrackFromVideo(V);
 			const FFMS_TrackTimeBase *TB = FFMS_GetTimeBase(T);
-			Env->SetVar("FFVFR_TIME", static_cast<int>(FFMS_GetFrameInfo(T, n)->PTS * static_cast<double>(TB->Num) / TB->Den));
+			Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFVFR_TIME"), static_cast<int>(FFMS_GetFrameInfo(T, n)->PTS * static_cast<double>(TB->Num) / TB->Den));
 		}
 
 		if (Frame == NULL)
 			Env->ThrowError("FFVideoSource: %s", E.Buffer);
 
-		Env->SetVar("FFPICT_TYPE", static_cast<int>(Frame->PictType));
+		Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFPICT_TYPE"), static_cast<int>(Frame->PictType));
 		OutputFrame(Frame, Dst, Env);
 	}
 
@@ -364,7 +367,7 @@ bool AvisynthVideoSource::GetParity(int n) {
 }
 
 AvisynthAudioSource::AvisynthAudioSource(const char *SourceFile, int Track, FFMS_Index *Index,
-										 int AdjustDelay, IScriptEnvironment* Env) {
+										 int AdjustDelay, const char *VarPrefix, IScriptEnvironment* Env) {
 	memset(&VI, 0, sizeof(VI));
 
 	char ErrorMsg[1024];
@@ -382,6 +385,11 @@ AvisynthAudioSource::AvisynthAudioSource(const char *SourceFile, int Track, FFMS
 	VI.num_audio_samples = AP->NumSamples;
 	VI.audio_samples_per_second = AP->SampleRate;
 
+	// casting to int should be safe; none of the channel constants are greater than INT_MAX
+	Env->SetVar(Env->Sprintf("%s%s", VarPrefix, "FFCHANNEL_LAYOUT"), static_cast<int>(AP->ChannelLayout));
+
+	Env->SetGlobalVar("FFVAR_PREFIX", VarPrefix);
+
 	switch (AP->SampleFormat) {
 		case FFMS_FMT_U8: VI.sample_type = SAMPLE_INT8; break;
 		case FFMS_FMT_S16: VI.sample_type = SAMPLE_INT16; break;
diff --git a/src/avisynth/avssources.h b/src/avisynth/avssources.h
index d5f3c60..97be5ff 100644
--- a/src/avisynth/avssources.h
+++ b/src/avisynth/avssources.h
@@ -41,6 +41,7 @@ private:
 	int FPSDen;
 	int RFFMode;
 	std::vector<FrameFields> FieldList;
+	const char *VarPrefix;
 
 	void InitOutputFormat(int ResizeToWidth, int ResizeToHeight,
 		const char *ResizerName, const char *ConvertToFormatName, IScriptEnvironment *Env);
@@ -50,7 +51,7 @@ public:
 	AvisynthVideoSource(const char *SourceFile, int Track, FFMS_Index *Index,
 		int FPSNum, int FPSDen, const char *PP, int Threads, int SeekMode, int RFFMode,
 		int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
-		const char *ConvertToFormatName, IScriptEnvironment* Env);
+		const char *ConvertToFormatName, const char *VarPrefix, IScriptEnvironment* Env);
 	~AvisynthVideoSource();
 	bool __stdcall GetParity(int n);
 	void __stdcall SetCacheHints(int cachehints, int frame_range) { }
@@ -65,7 +66,7 @@ private:
 	FFMS_AudioSource *A;
 public:
 	AvisynthAudioSource(const char *SourceFile, int Track, FFMS_Index *Index,
-		int AdjustDelay, IScriptEnvironment* Env);
+		int AdjustDelay, const char *VarPrefix, IScriptEnvironment* Env);
 	~AvisynthAudioSource();
 	bool __stdcall GetParity(int n) { return false; }
 	void __stdcall SetCacheHints(int cachehints, int frame_range) { }
diff --git a/src/avisynth/ffpp.cpp b/src/avisynth/ffpp.cpp
index bd03a74..92db260 100644
--- a/src/avisynth/ffpp.cpp
+++ b/src/avisynth/ffpp.cpp
@@ -66,8 +66,10 @@ FFPP::FFPP(PClip AChild, const char *PP, IScriptEnvironment *Env) : GenericVideo
 		Flags |= PP_FORMAT_420;
 	} else if (vi.IsYUY2()) {
 		Flags |= PP_FORMAT_422;
-		SWSTo422P = GetSwsContext(vi.width, vi.height, PIX_FMT_YUYV422, vi.width, vi.height, PIX_FMT_YUV422P, Flags | SWS_BICUBIC);
-		SWSFrom422P = GetSwsContext(vi.width, vi.height, PIX_FMT_YUV422P, vi.width, vi.height, PIX_FMT_YUYV422, Flags | SWS_BICUBIC);
+		SWSTo422P = GetSwsContext(vi.width, vi.height, PIX_FMT_YUYV422, vi.width, vi.height, PIX_FMT_YUV422P, Flags | SWS_BICUBIC,
+						GetSwsAssumedColorSpace(vi.width, vi.height));
+		SWSFrom422P = GetSwsContext(vi.width, vi.height, PIX_FMT_YUV422P, vi.width, vi.height, PIX_FMT_YUYV422, Flags | SWS_BICUBIC,
+						GetSwsAssumedColorSpace(vi.width, vi.height));
 		avpicture_alloc(&InputPicture, PIX_FMT_YUV422P, vi.width, vi.height);
 		avpicture_alloc(&OutputPicture, PIX_FMT_YUV422P, vi.width, vi.height);
 	} else {
diff --git a/src/avisynth/ffswscale.cpp b/src/avisynth/ffswscale.cpp
index cd2c869..885add3 100644
--- a/src/avisynth/ffswscale.cpp
+++ b/src/avisynth/ffswscale.cpp
@@ -87,7 +87,7 @@ SWScale::SWScale(PClip Child, int ResizeToWidth, int ResizeToHeight, const char
 		Env->ThrowError("SWScale: mod 2 output width required");
 
 	Context = GetSwsContext(OrigWidth, OrigHeight, ConvertFromFormat, vi.width, vi.height, ConvertToFormat, 
-		AvisynthToSWSCPUFlags(Env->GetCPUFlags()) | Resizer);
+		AvisynthToSWSCPUFlags(Env->GetCPUFlags()) | Resizer, GetSwsAssumedColorSpace(OrigWidth, OrigHeight));
 	if (Context == NULL)
 		Env->ThrowError("SWScale: Context creation failed");
 }
diff --git a/src/config/config.h.in b/src/config/config.h.in
index f8b07dd..f76c3cf 100644
--- a/src/config/config.h.in
+++ b/src/config/config.h.in
@@ -8,6 +8,9 @@
 /* Define to 1 if using `alloca.c'. */
 #undef C_ALLOCA
 
+/* Building with FFmpeg? */
+#undef FFMS_USE_FFMPEG_COMPAT
+
 /* Define to 1 if you have `alloca', as a function or macro. */
 #undef HAVE_ALLOCA
 
@@ -84,8 +87,5 @@
 /* Version number of package */
 #undef VERSION
 
-/* Building with postproc? */
-#undef WITH_LIBPOSTPROC
-
 /* Define to `unsigned int' if <sys/types.h> does not define. */
 #undef size_t
diff --git a/src/core/audiosource.cpp b/src/core/audiosource.cpp
index 586f72c..ec124e4 100644
--- a/src/core/audiosource.cpp
+++ b/src/core/audiosource.cpp
@@ -35,7 +35,6 @@ FFMS_AudioSource::FFMS_AudioSource(const char *SourceFile, FFMS_Index &Index, in
 , SeekOffset(0)
 , DecodingBuffer(AVCODEC_MAX_AUDIO_FRAME_SIZE * 10)
 , Index(Index)
-, Frames(Index[0]) // dummy initialization
 {
 	if (Track < 0 || Track >= static_cast<int>(Index.size()))
 		throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
@@ -61,7 +60,7 @@ FFMS_AudioSource::FFMS_AudioSource(const char *SourceFile, FFMS_Index &Index, in
 
 #define EXCESSIVE_CACHE_SIZE 400
 
-void FFMS_AudioSource::Init(FFMS_Index &Index, int DelayMode) {
+void FFMS_AudioSource::Init(const FFMS_Index &Index, int DelayMode) {
 	// The first packet after a seek is often decoded incorrectly, which
 	// makes it impossible to ever correctly seek back to the beginning, so
 	// store the first block now
diff --git a/src/core/audiosource.h b/src/core/audiosource.h
index 3f83156..9fd276f 100644
--- a/src/core/audiosource.h
+++ b/src/core/audiosource.h
@@ -101,13 +101,13 @@ protected:
 	// Buffer which audio is decoded into
 	AlignedBuffer<uint8_t> DecodingBuffer;
 	FFMS_Index &Index;
-	FFMS_Track &Frames;
+	FFMS_Track Frames;
 	FFCodecContext CodecContext;
 	FFMS_AudioProperties AP;
 
 	void DecodeNextBlock();
 	// Initialization which has to be done after the codec is opened
-	void Init(FFMS_Index &Index, int DelayMode);
+	void Init(const FFMS_Index &Index, int DelayMode);
 
 	FFMS_AudioSource(const char *SourceFile, FFMS_Index &Index, int Track);
 
diff --git a/src/core/codectype.cpp b/src/core/codectype.cpp
new file mode 100644
index 0000000..4e2de27
--- /dev/null
+++ b/src/core/codectype.cpp
@@ -0,0 +1,459 @@
+//  Copyright (c) 2007-2011 Fredrik Mellbin
+//
+//  Permission is hereby granted, free of charge, to any person obtaining a copy
+//  of this software and associated documentation files (the "Software"), to deal
+//  in the Software without restriction, including without limitation the rights
+//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+//  copies of the Software, and to permit persons to whom the Software is
+//  furnished to do so, subject to the following conditions:
+//
+//  The above copyright notice and this permission notice shall be included in
+//  all copies or substantial portions of the Software.
+//
+//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+//  THE SOFTWARE.
+
+#include "codectype.h"
+
+#include "matroskaparser.h"
+#include "utils.h"
+
+typedef struct CodecTags {
+	char str[20];
+	CodecID id;
+} CodecTags;
+
+static const CodecTags mkv_codec_tags[] = {
+	{"A_AAC"            , CODEC_ID_AAC},
+	{"A_AC3"            , CODEC_ID_AC3},
+	{"A_DTS"            , CODEC_ID_DTS},
+	{"A_EAC3"           , CODEC_ID_EAC3},
+	{"A_FLAC"           , CODEC_ID_FLAC},
+	{"A_MLP"            , CODEC_ID_MLP},
+	{"A_MPEG/L2"        , CODEC_ID_MP2},
+	{"A_MPEG/L1"        , CODEC_ID_MP2},
+	{"A_MPEG/L3"        , CODEC_ID_MP3},
+	{"A_PCM/FLOAT/IEEE" , CODEC_ID_PCM_F32LE},
+	{"A_PCM/FLOAT/IEEE" , CODEC_ID_PCM_F64LE},
+	{"A_PCM/INT/BIG"    , CODEC_ID_PCM_S16BE},
+	{"A_PCM/INT/BIG"    , CODEC_ID_PCM_S24BE},
+	{"A_PCM/INT/BIG"    , CODEC_ID_PCM_S32BE},
+	{"A_PCM/INT/LIT"    , CODEC_ID_PCM_S16LE},
+	{"A_PCM/INT/LIT"    , CODEC_ID_PCM_S24LE},
+	{"A_PCM/INT/LIT"    , CODEC_ID_PCM_S32LE},
+	{"A_PCM/INT/LIT"    , CODEC_ID_PCM_U8},
+	{"A_QUICKTIME/QDM2" , CODEC_ID_QDM2},
+	{"A_REAL/14_4"      , CODEC_ID_RA_144},
+	{"A_REAL/28_8"      , CODEC_ID_RA_288},
+	{"A_REAL/ATRC"      , CODEC_ID_ATRAC3},
+	{"A_REAL/COOK"      , CODEC_ID_COOK},
+	{"A_REAL/SIPR"      , CODEC_ID_SIPR},
+	{"A_TRUEHD"         , CODEC_ID_TRUEHD},
+	{"A_TTA1"           , CODEC_ID_TTA},
+	{"A_VORBIS"         , CODEC_ID_VORBIS},
+	{"A_WAVPACK4"       , CODEC_ID_WAVPACK},
+
+	{"S_TEXT/UTF8"      , CODEC_ID_TEXT},
+#if (LIBAVCODEC_VERSION_INT) >= (AV_VERSION_INT(52, 101, 0))
+	{"S_TEXT/UTF8"      , CODEC_ID_SRT},
+#endif
+	{"S_TEXT/ASCII"     , CODEC_ID_TEXT},
+	{"S_TEXT/ASS"       , CODEC_ID_SSA},
+	{"S_TEXT/SSA"       , CODEC_ID_SSA},
+	{"S_ASS"            , CODEC_ID_SSA},
+	{"S_SSA"            , CODEC_ID_SSA},
+	{"S_VOBSUB"         , CODEC_ID_DVD_SUBTITLE},
+	{"S_HDMV/PGS"       , CODEC_ID_HDMV_PGS_SUBTITLE},
+
+	{"V_DIRAC"          , CODEC_ID_DIRAC},
+	{"V_MJPEG"          , CODEC_ID_MJPEG},
+	{"V_MPEG1"          , CODEC_ID_MPEG1VIDEO},
+	{"V_MPEG2"          , CODEC_ID_MPEG2VIDEO},
+	{"V_MPEG4/ISO/ASP"  , CODEC_ID_MPEG4},
+	{"V_MPEG4/ISO/AP"   , CODEC_ID_MPEG4},
+	{"V_MPEG4/ISO/SP"   , CODEC_ID_MPEG4},
+	{"V_MPEG4/ISO/AVC"  , CODEC_ID_H264},
+	{"V_MPEG4/MS/V3"    , CODEC_ID_MSMPEG4V3},
+	{"V_REAL/RV10"      , CODEC_ID_RV10},
+	{"V_REAL/RV20"      , CODEC_ID_RV20},
+	{"V_REAL/RV30"      , CODEC_ID_RV30},
+	{"V_REAL/RV40"      , CODEC_ID_RV40},
+	{"V_SNOW"           , CODEC_ID_SNOW},
+	{"V_THEORA"         , CODEC_ID_THEORA},
+	{"V_UNCOMPRESSED"   , CODEC_ID_RAWVIDEO},
+	{"V_VP8"            , CODEC_ID_VP8},
+
+	{""                 , CODEC_ID_NONE}
+};
+
+typedef struct AVCodecTag {
+	enum CodecID id;
+	unsigned int tag;
+} AVCodecTag;
+
+static const AVCodecTag codec_bmp_tags[] = {
+	{ CODEC_ID_H264,         MKTAG('H', '2', '6', '4') },
+	{ CODEC_ID_H264,         MKTAG('h', '2', '6', '4') },
+	{ CODEC_ID_H264,         MKTAG('X', '2', '6', '4') },
+	{ CODEC_ID_H264,         MKTAG('x', '2', '6', '4') },
+	{ CODEC_ID_H264,         MKTAG('a', 'v', 'c', '1') },
+	{ CODEC_ID_H264,         MKTAG('D', 'A', 'V', 'C') },
+	{ CODEC_ID_H264,         MKTAG('V', 'S', 'S', 'H') },
+	{ CODEC_ID_H264,         MKTAG('Q', '2', '6', '4') }, /* QNAP surveillance system */
+	{ CODEC_ID_H263,         MKTAG('H', '2', '6', '3') },
+	{ CODEC_ID_H263,         MKTAG('X', '2', '6', '3') },
+	{ CODEC_ID_H263,         MKTAG('T', '2', '6', '3') },
+	{ CODEC_ID_H263,         MKTAG('L', '2', '6', '3') },
+	{ CODEC_ID_H263,         MKTAG('V', 'X', '1', 'K') },
+	{ CODEC_ID_H263,         MKTAG('Z', 'y', 'G', 'o') },
+	{ CODEC_ID_H263,         MKTAG('M', '2', '6', '3') },
+	{ CODEC_ID_H263P,        MKTAG('H', '2', '6', '3') },
+	{ CODEC_ID_H263I,        MKTAG('I', '2', '6', '3') }, /* intel h263 */
+	{ CODEC_ID_H261,         MKTAG('H', '2', '6', '1') },
+	{ CODEC_ID_H263P,        MKTAG('U', '2', '6', '3') },
+	{ CODEC_ID_H263P,        MKTAG('v', 'i', 'v', '1') },
+	{ CODEC_ID_MPEG4,        MKTAG('F', 'M', 'P', '4') },
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'I', 'V', 'X') },
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'X', '5', '0') },
+	{ CODEC_ID_MPEG4,        MKTAG('X', 'V', 'I', 'D') },
+	{ CODEC_ID_MPEG4,        MKTAG('M', 'P', '4', 'S') },
+	{ CODEC_ID_MPEG4,        MKTAG('M', '4', 'S', '2') },
+	{ CODEC_ID_MPEG4,        MKTAG( 4 ,  0 ,  0 ,  0 ) }, /* some broken avi use this */
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'I', 'V', '1') },
+	{ CODEC_ID_MPEG4,        MKTAG('B', 'L', 'Z', '0') },
+	{ CODEC_ID_MPEG4,        MKTAG('m', 'p', '4', 'v') },
+	{ CODEC_ID_MPEG4,        MKTAG('U', 'M', 'P', '4') },
+	{ CODEC_ID_MPEG4,        MKTAG('W', 'V', '1', 'F') },
+	{ CODEC_ID_MPEG4,        MKTAG('S', 'E', 'D', 'G') },
+	{ CODEC_ID_MPEG4,        MKTAG('R', 'M', 'P', '4') },
+	{ CODEC_ID_MPEG4,        MKTAG('3', 'I', 'V', '2') },
+	{ CODEC_ID_MPEG4,        MKTAG('W', 'A', 'W', 'V') }, /* WaWv MPEG-4 Video Codec */
+	{ CODEC_ID_MPEG4,        MKTAG('F', 'F', 'D', 'S') },
+	{ CODEC_ID_MPEG4,        MKTAG('F', 'V', 'F', 'W') },
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'C', 'O', 'D') },
+	{ CODEC_ID_MPEG4,        MKTAG('M', 'V', 'X', 'M') },
+	{ CODEC_ID_MPEG4,        MKTAG('P', 'M', '4', 'V') },
+	{ CODEC_ID_MPEG4,        MKTAG('S', 'M', 'P', '4') },
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'X', 'G', 'M') },
+	{ CODEC_ID_MPEG4,        MKTAG('V', 'I', 'D', 'M') },
+	{ CODEC_ID_MPEG4,        MKTAG('M', '4', 'T', '3') },
+	{ CODEC_ID_MPEG4,        MKTAG('G', 'E', 'O', 'X') },
+	{ CODEC_ID_MPEG4,        MKTAG('H', 'D', 'X', '4') }, /* flipped video */
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'M', 'K', '2') },
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'I', 'G', 'I') },
+	{ CODEC_ID_MPEG4,        MKTAG('I', 'N', 'M', 'C') },
+	{ CODEC_ID_MPEG4,        MKTAG('E', 'P', 'H', 'V') }, /* Ephv MPEG-4 */
+	{ CODEC_ID_MPEG4,        MKTAG('E', 'M', '4', 'A') },
+	{ CODEC_ID_MPEG4,        MKTAG('M', '4', 'C', 'C') }, /* Divio MPEG-4 */
+	{ CODEC_ID_MPEG4,        MKTAG('S', 'N', '4', '0') },
+	{ CODEC_ID_MPEG4,        MKTAG('V', 'S', 'P', 'X') },
+	{ CODEC_ID_MPEG4,        MKTAG('U', 'L', 'D', 'X') },
+	{ CODEC_ID_MPEG4,        MKTAG('G', 'E', 'O', 'V') },
+	{ CODEC_ID_MPEG4,        MKTAG('S', 'I', 'P', 'P') }, /* Samsung SHR-6040 */
+	{ CODEC_ID_MPEG4,        MKTAG('X', 'V', 'I', 'X') },
+	{ CODEC_ID_MPEG4,        MKTAG('D', 'r', 'e', 'X') },
+	{ CODEC_ID_MPEG4,        MKTAG('Q', 'M', 'P', '4') }, /* QNAP Systems */
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('M', 'P', '4', '3') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('D', 'I', 'V', '3') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('M', 'P', 'G', '3') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('D', 'I', 'V', '5') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('D', 'I', 'V', '6') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('D', 'I', 'V', '4') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('D', 'V', 'X', '3') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('A', 'P', '4', '1') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('C', 'O', 'L', '1') },
+	{ CODEC_ID_MSMPEG4V3,    MKTAG('C', 'O', 'L', '0') },
+	{ CODEC_ID_MSMPEG4V2,    MKTAG('M', 'P', '4', '2') },
+	{ CODEC_ID_MSMPEG4V2,    MKTAG('D', 'I', 'V', '2') },
+	{ CODEC_ID_MSMPEG4V1,    MKTAG('M', 'P', 'G', '4') },
+	{ CODEC_ID_MSMPEG4V1,    MKTAG('M', 'P', '4', '1') },
+	{ CODEC_ID_WMV1,         MKTAG('W', 'M', 'V', '1') },
+	{ CODEC_ID_WMV2,         MKTAG('W', 'M', 'V', '2') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 's', 'd') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'h', 'd') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'h', '1') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 's', 'l') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', '2', '5') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', '5', '0') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('c', 'd', 'v', 'c') }, /* Canopus DV */
+	{ CODEC_ID_DVVIDEO,      MKTAG('C', 'D', 'V', 'H') }, /* Canopus DV */
+	{ CODEC_ID_DVVIDEO,      MKTAG('C', 'D', 'V', '5') }, /* Canopus DV */
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'c', ' ') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'c', 's') },
+	{ CODEC_ID_DVVIDEO,      MKTAG('d', 'v', 'h', '1') },
+	{ CODEC_ID_MPEG1VIDEO,   MKTAG('m', 'p', 'g', '1') },
+	{ CODEC_ID_MPEG1VIDEO,   MKTAG('m', 'p', 'g', '2') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('m', 'p', 'g', '2') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('M', 'P', 'E', 'G') },
+	{ CODEC_ID_MPEG1VIDEO,   MKTAG('P', 'I', 'M', '1') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('P', 'I', 'M', '2') },
+	{ CODEC_ID_MPEG1VIDEO,   MKTAG('V', 'C', 'R', '2') },
+	{ CODEC_ID_MPEG1VIDEO,   MKTAG( 1 ,  0 ,  0 ,  16) },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG( 2 ,  0 ,  0 ,  16) },
+	{ CODEC_ID_MPEG4,        MKTAG( 4 ,  0 ,  0 ,  16) },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('D', 'V', 'R', ' ') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('M', 'M', 'E', 'S') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('L', 'M', 'P', '2') }, /* Lead MPEG2 in avi */
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('s', 'l', 'i', 'f') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('E', 'M', '2', 'V') },
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('M', '7', '0', '1') }, /* Matrox MPEG2 intra-only */
+	{ CODEC_ID_MPEG2VIDEO,   MKTAG('m', 'p', 'g', 'v') },
+	{ CODEC_ID_MJPEG,        MKTAG('M', 'J', 'P', 'G') },
+	{ CODEC_ID_MJPEG,        MKTAG('L', 'J', 'P', 'G') },
+	{ CODEC_ID_MJPEG,        MKTAG('d', 'm', 'b', '1') },
+	{ CODEC_ID_MJPEG,        MKTAG('m', 'j', 'p', 'a') },
+	{ CODEC_ID_LJPEG,        MKTAG('L', 'J', 'P', 'G') },
+	{ CODEC_ID_MJPEG,        MKTAG('J', 'P', 'G', 'L') }, /* Pegasus lossless JPEG */
+	{ CODEC_ID_JPEGLS,       MKTAG('M', 'J', 'L', 'S') }, /* JPEG-LS custom FOURCC for avi - encoder */
+	{ CODEC_ID_JPEGLS,       MKTAG('M', 'J', 'P', 'G') },
+	{ CODEC_ID_MJPEG,        MKTAG('M', 'J', 'L', 'S') }, /* JPEG-LS custom FOURCC for avi - decoder */
+	{ CODEC_ID_MJPEG,        MKTAG('j', 'p', 'e', 'g') },
+	{ CODEC_ID_MJPEG,        MKTAG('I', 'J', 'P', 'G') },
+	{ CODEC_ID_MJPEG,        MKTAG('A', 'V', 'R', 'n') },
+	{ CODEC_ID_MJPEG,        MKTAG('A', 'C', 'D', 'V') },
+	{ CODEC_ID_MJPEG,        MKTAG('Q', 'I', 'V', 'G') },
+	{ CODEC_ID_MJPEG,        MKTAG('S', 'L', 'M', 'J') }, /* SL M-JPEG */
+	{ CODEC_ID_MJPEG,        MKTAG('C', 'J', 'P', 'G') }, /* Creative Webcam JPEG */
+	{ CODEC_ID_MJPEG,        MKTAG('I', 'J', 'L', 'V') }, /* Intel JPEG Library Video Codec */
+	{ CODEC_ID_MJPEG,        MKTAG('M', 'V', 'J', 'P') }, /* Midvid JPEG Video Codec */
+	{ CODEC_ID_MJPEG,        MKTAG('A', 'V', 'I', '1') },
+	{ CODEC_ID_MJPEG,        MKTAG('A', 'V', 'I', '2') },
+	{ CODEC_ID_MJPEG,        MKTAG('M', 'T', 'S', 'J') },
+	{ CODEC_ID_MJPEG,        MKTAG('Z', 'J', 'P', 'G') }, /* Paradigm Matrix M-JPEG Codec */
+	{ CODEC_ID_MJPEG,        MKTAG('M', 'M', 'J', 'P') },
+	{ CODEC_ID_HUFFYUV,      MKTAG('H', 'F', 'Y', 'U') },
+	{ CODEC_ID_FFVHUFF,      MKTAG('F', 'F', 'V', 'H') },
+	{ CODEC_ID_CYUV,         MKTAG('C', 'Y', 'U', 'V') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG( 0 ,  0 ,  0 ,  0 ) },
+	{ CODEC_ID_RAWVIDEO,     MKTAG( 3 ,  0 ,  0 ,  0 ) },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('I', '4', '2', '0') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'U', 'Y', '2') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', '4', '2', '2') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('V', '4', '2', '2') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'U', 'N', 'V') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('U', 'Y', 'N', 'V') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('U', 'Y', 'N', 'Y') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('u', 'y', 'v', '1') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('2', 'V', 'u', '1') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('2', 'v', 'u', 'y') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('y', 'u', 'v', 's') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('P', '4', '2', '2') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', '1', '2') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', '1', '6') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', '2', '4') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('U', 'Y', 'V', 'Y') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('V', 'Y', 'U', 'Y') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('I', 'Y', 'U', 'V') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', '8', '0', '0') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', '8', ' ', ' ') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('H', 'D', 'Y', 'C') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', 'U', '9') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('V', 'D', 'T', 'Z') }, /* SoftLab-NSK VideoTizer */
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', '4', '1', '1') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('N', 'V', '1', '2') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('N', 'V', '2', '1') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', '4', '1', 'B') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', '4', '2', 'B') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'U', 'V', '9') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', 'U', '9') },
+	{ CODEC_ID_RAWVIDEO,     MKTAG('a', 'u', 'v', '2') },
+	{ CODEC_ID_FRWU,         MKTAG('F', 'R', 'W', 'U') },
+#if (LIBAVCODEC_VERSION_INT) >= (AV_VERSION_INT(52, 89, 0))
+	{ CODEC_ID_R10K,         MKTAG('R', '1', '0', 'k') },
+#endif
+	{ CODEC_ID_R210,         MKTAG('r', '2', '1', '0') },
+	{ CODEC_ID_V210,         MKTAG('v', '2', '1', '0') },
+#if VERSION_CHECK(LIBAVCODEC_VERSION_INT, >=, 53, 28, 0, 53, 44, 0)
+	{ CODEC_ID_V410,         MKTAG('v', '2', '1', '0') },
+#endif
+	{ CODEC_ID_INDEO3,       MKTAG('I', 'V', '3', '1') },
+	{ CODEC_ID_INDEO3,       MKTAG('I', 'V', '3', '2') },
+	{ CODEC_ID_INDEO4,       MKTAG('I', 'V', '4', '1') },
+	{ CODEC_ID_INDEO5,       MKTAG('I', 'V', '5', '0') },
+	{ CODEC_ID_VP3,          MKTAG('V', 'P', '3', '1') },
+	{ CODEC_ID_VP3,          MKTAG('V', 'P', '3', '0') },
+	{ CODEC_ID_VP5,          MKTAG('V', 'P', '5', '0') },
+	{ CODEC_ID_VP6,          MKTAG('V', 'P', '6', '0') },
+	{ CODEC_ID_VP6,          MKTAG('V', 'P', '6', '1') },
+	{ CODEC_ID_VP6,          MKTAG('V', 'P', '6', '2') },
+	{ CODEC_ID_VP6F,         MKTAG('V', 'P', '6', 'F') },
+	{ CODEC_ID_VP6F,         MKTAG('F', 'L', 'V', '4') },
+	{ CODEC_ID_VP8,          MKTAG('V', 'P', '8', '0') },
+	{ CODEC_ID_ASV1,         MKTAG('A', 'S', 'V', '1') },
+	{ CODEC_ID_ASV2,         MKTAG('A', 'S', 'V', '2') },
+	{ CODEC_ID_VCR1,         MKTAG('V', 'C', 'R', '1') },
+	{ CODEC_ID_FFV1,         MKTAG('F', 'F', 'V', '1') },
+	{ CODEC_ID_XAN_WC4,      MKTAG('X', 'x', 'a', 'n') },
+	{ CODEC_ID_MIMIC,        MKTAG('L', 'M', '2', '0') },
+	{ CODEC_ID_MSRLE,        MKTAG('m', 'r', 'l', 'e') },
+	{ CODEC_ID_MSRLE,        MKTAG( 1 ,  0 ,  0 ,  0 ) },
+	{ CODEC_ID_MSRLE,        MKTAG( 2 ,  0 ,  0 ,  0 ) },
+	{ CODEC_ID_MSVIDEO1,     MKTAG('M', 'S', 'V', 'C') },
+	{ CODEC_ID_MSVIDEO1,     MKTAG('m', 's', 'v', 'c') },
+	{ CODEC_ID_MSVIDEO1,     MKTAG('C', 'R', 'A', 'M') },
+	{ CODEC_ID_MSVIDEO1,     MKTAG('c', 'r', 'a', 'm') },
+	{ CODEC_ID_MSVIDEO1,     MKTAG('W', 'H', 'A', 'M') },
+	{ CODEC_ID_MSVIDEO1,     MKTAG('w', 'h', 'a', 'm') },
+	{ CODEC_ID_CINEPAK,      MKTAG('c', 'v', 'i', 'd') },
+	{ CODEC_ID_TRUEMOTION1,  MKTAG('D', 'U', 'C', 'K') },
+	{ CODEC_ID_TRUEMOTION1,  MKTAG('P', 'V', 'E', 'Z') },
+	{ CODEC_ID_MSZH,         MKTAG('M', 'S', 'Z', 'H') },
+	{ CODEC_ID_ZLIB,         MKTAG('Z', 'L', 'I', 'B') },
+	{ CODEC_ID_SNOW,         MKTAG('S', 'N', 'O', 'W') },
+	{ CODEC_ID_4XM,          MKTAG('4', 'X', 'M', 'V') },
+	{ CODEC_ID_FLV1,         MKTAG('F', 'L', 'V', '1') },
+	{ CODEC_ID_FLASHSV,      MKTAG('F', 'S', 'V', '1') },
+	{ CODEC_ID_SVQ1,         MKTAG('s', 'v', 'q', '1') },
+	{ CODEC_ID_TSCC,         MKTAG('t', 's', 'c', 'c') },
+	{ CODEC_ID_ULTI,         MKTAG('U', 'L', 'T', 'I') },
+	{ CODEC_ID_VIXL,         MKTAG('V', 'I', 'X', 'L') },
+	{ CODEC_ID_QPEG,         MKTAG('Q', 'P', 'E', 'G') },
+	{ CODEC_ID_QPEG,         MKTAG('Q', '1', '.', '0') },
+	{ CODEC_ID_QPEG,         MKTAG('Q', '1', '.', '1') },
+	{ CODEC_ID_WMV3,         MKTAG('W', 'M', 'V', '3') },
+#if (LIBAVCODEC_VERSION_INT) >= (AV_VERSION_INT(53, 9, 0))
+	{ CODEC_ID_WMV3IMAGE,    MKTAG('W', 'M', 'V', 'P') },
+#endif
+	{ CODEC_ID_VC1,          MKTAG('W', 'V', 'C', '1') },
+	{ CODEC_ID_VC1,          MKTAG('W', 'M', 'V', 'A') },
+#if (LIBAVCODEC_VERSION_INT) >= (AV_VERSION_INT(53, 9, 0))
+	{ CODEC_ID_VC1IMAGE,     MKTAG('W', 'V', 'P', '2') },
+#endif
+	{ CODEC_ID_LOCO,         MKTAG('L', 'O', 'C', 'O') },
+	{ CODEC_ID_WNV1,         MKTAG('W', 'N', 'V', '1') },
+	{ CODEC_ID_AASC,         MKTAG('A', 'A', 'S', 'C') },
+	{ CODEC_ID_INDEO2,       MKTAG('R', 'T', '2', '1') },
+	{ CODEC_ID_FRAPS,        MKTAG('F', 'P', 'S', '1') },
+	{ CODEC_ID_THEORA,       MKTAG('t', 'h', 'e', 'o') },
+	{ CODEC_ID_TRUEMOTION2,  MKTAG('T', 'M', '2', '0') },
+	{ CODEC_ID_CSCD,         MKTAG('C', 'S', 'C', 'D') },
+	{ CODEC_ID_ZMBV,         MKTAG('Z', 'M', 'B', 'V') },
+	{ CODEC_ID_KMVC,         MKTAG('K', 'M', 'V', 'C') },
+	{ CODEC_ID_CAVS,         MKTAG('C', 'A', 'V', 'S') },
+	{ CODEC_ID_JPEG2000,     MKTAG('m', 'j', 'p', '2') },
+	{ CODEC_ID_JPEG2000,     MKTAG('M', 'J', '2', 'C') },
+	{ CODEC_ID_JPEG2000,     MKTAG('L', 'J', '2', 'C') },
+	{ CODEC_ID_JPEG2000,     MKTAG('L', 'J', '2', 'K') },
+	{ CODEC_ID_VMNC,         MKTAG('V', 'M', 'n', 'c') },
+	{ CODEC_ID_TARGA,        MKTAG('t', 'g', 'a', ' ') },
+	{ CODEC_ID_PNG,          MKTAG('M', 'P', 'N', 'G') },
+	{ CODEC_ID_PNG,          MKTAG('P', 'N', 'G', '1') },
+	{ CODEC_ID_CLJR,         MKTAG('c', 'l', 'j', 'r') },
+	{ CODEC_ID_DIRAC,        MKTAG('d', 'r', 'a', 'c') },
+	{ CODEC_ID_RPZA,         MKTAG('a', 'z', 'p', 'r') },
+	{ CODEC_ID_RPZA,         MKTAG('R', 'P', 'Z', 'A') },
+	{ CODEC_ID_RPZA,         MKTAG('r', 'p', 'z', 'a') },
+	{ CODEC_ID_SP5X,         MKTAG('S', 'P', '5', '4') },
+	{ CODEC_ID_AURA,         MKTAG('A', 'U', 'R', 'A') },
+	{ CODEC_ID_AURA2,        MKTAG('A', 'U', 'R', '2') },
+	{ CODEC_ID_DPX,          MKTAG('d', 'p', 'x', ' ') },
+	{ CODEC_ID_KGV1,         MKTAG('K', 'G', 'V', '1') },
+#if (LIBAVCODEC_VERSION_INT) >= (AV_VERSION_INT(52, 108, 0))
+	{ CODEC_ID_LAGARITH,     MKTAG('L', 'A', 'G', 'S') },
+#endif
+#ifdef FFMS_USE_FFMPEG_COMPAT
+	{ CODEC_ID_G2M,          MKTAG('G', '2', 'M', '2') },
+	{ CODEC_ID_G2M,          MKTAG('G', '2', 'M', '3') },
+	{ CODEC_ID_G2M,          MKTAG('G', '2', 'M', '4') },
+#endif
+	{ CODEC_ID_AMV,          MKTAG('A', 'M', 'V', 'F') },
+#if VERSION_CHECK(LIBAVCODEC_VERSION_INT, >, 53, 12, 2, 53, 20, 1)
+	{ CODEC_ID_UTVIDEO,      MKTAG('U', 'L', 'R', 'A') },
+	{ CODEC_ID_UTVIDEO,      MKTAG('U', 'L', 'R', 'G') },
+	{ CODEC_ID_UTVIDEO,      MKTAG('U', 'L', 'Y', '0') },
+	{ CODEC_ID_UTVIDEO,      MKTAG('U', 'L', 'Y', '2') },
+#endif
+#if VERSION_CHECK(LIBAVCODEC_VERSION_INT, >=, 53, 19, 0, 53, 32, 0)
+	{ CODEC_ID_VBLE,         MKTAG('V', 'B', 'L', 'E') },
+#endif
+#if defined(FFMS_USE_FFMPEG_COMPAT) && (LIBAVCODEC_VERSION_INT) >= (AV_VERSION_INT(53, 43, 0))
+	{ CODEC_ID_ESCAPE130,    MKTAG('E', '1', '3', '0') },
+#endif
+#if VERSION_CHECK(LIBAVCODEC_VERSION_INT, >=, 53, 28, 0, 53, 43, 0)
+	{ CODEC_ID_DXTORY,       MKTAG('x', 't', 'o', 'r') },
+#endif
+	{ CODEC_ID_NONE,         0 }
+};
+
+FFMS_TrackType HaaliTrackTypeToFFTrackType(int TT) {
+	switch (TT) {
+		case TT_VIDEO: return FFMS_TYPE_VIDEO; break;
+		case TT_AUDIO: return FFMS_TYPE_AUDIO; break;
+		case TT_SUB: return FFMS_TYPE_SUBTITLE; break;
+		default: return FFMS_TYPE_UNKNOWN;
+	}
+}
+
+const char *GetLAVCSampleFormatName(AVSampleFormat s) {
+	switch (s) {
+		case AV_SAMPLE_FMT_U8:	return "8-bit unsigned integer";
+		case AV_SAMPLE_FMT_S16:	return "16-bit signed integer";
+		case AV_SAMPLE_FMT_S32:	return "32-bit signed integer";
+		case AV_SAMPLE_FMT_FLT:	return "Single-precision floating point";
+		case AV_SAMPLE_FMT_DBL:	return "Double-precision floating point";
+		default:				return "Unknown";
+	}
+}
+
+CodecID MatroskaToFFCodecID(char *Codec, void *CodecPrivate, unsigned int FourCC, unsigned int BitsPerSample) {
+	/* Look up native codecs */
+	for(int i = 0; mkv_codec_tags[i].id != CODEC_ID_NONE; i++){
+		if(!strncmp(mkv_codec_tags[i].str, Codec,
+			strlen(mkv_codec_tags[i].str))) {
+
+				// Uncompressed and exotic format fixup
+				// This list is incomplete
+				CodecID CID = mkv_codec_tags[i].id;
+				switch (CID) {
+					case CODEC_ID_PCM_S16LE:
+						switch (BitsPerSample) {
+					case 8: CID = CODEC_ID_PCM_S8; break;
+					case 16: CID = CODEC_ID_PCM_S16LE; break;
+					case 24: CID = CODEC_ID_PCM_S24LE; break;
+					case 32: CID = CODEC_ID_PCM_S32LE; break;
+						}
+						break;
+					case CODEC_ID_PCM_S16BE:
+						switch (BitsPerSample) {
+					case 8: CID = CODEC_ID_PCM_S8; break;
+					case 16: CID = CODEC_ID_PCM_S16BE; break;
+					case 24: CID = CODEC_ID_PCM_S24BE; break;
+					case 32: CID = CODEC_ID_PCM_S32BE; break;
+						}
+						break;
+					default:
+						break;
+				}
+
+				return CID;
+		}
+	}
+
+	/* Video codecs for "avi in mkv" mode */
+	const AVCodecTag *const tags[] = { codec_bmp_tags, 0 };
+
+	if (!strcmp(Codec, "V_MS/VFW/FOURCC")) {
+		FFMS_BITMAPINFOHEADER *b = reinterpret_cast<FFMS_BITMAPINFOHEADER *>(CodecPrivate);
+		return av_codec_get_id(tags, b->biCompression);
+	}
+
+	if (!strcmp(Codec, "V_FOURCC")) {
+		return av_codec_get_id(tags, FourCC);
+	}
+
+	// FIXME
+	/* Audio codecs for "acm in mkv" mode */
+	//#include "Mmreg.h"
+	//((WAVEFORMATEX *)TI->CodecPrivate)->wFormatTag
+
+	/* Fixup for uncompressed video formats */
+
+	/* Fixup for uncompressed audio formats */
+
+	return CODEC_ID_NONE;
+}
diff --git a/src/avisynth/avsutils.h b/src/core/codectype.h
similarity index 79%
copy from src/avisynth/avsutils.h
copy to src/core/codectype.h
index 3337fd3..e6c3c4b 100644
--- a/src/avisynth/avsutils.h
+++ b/src/core/codectype.h
@@ -1,4 +1,4 @@
-//  Copyright (c) 2009 Fredrik Mellbin
+//  Copyright (c) 2007-2011 Fredrik Mellbin
 //
 //  Permission is hereby granted, free of charge, to any person obtaining a copy
 //  of this software and associated documentation files (the "Software"), to deal
@@ -18,18 +18,14 @@
 //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 //  THE SOFTWARE.
 
-#ifndef AVSUTILS_H
-#define AVSUTILS_H
+#include "ffms.h"
 
 extern "C" {
 #include <libavcodec/avcodec.h>
-}
+};
 
 #include "ffmscompat.h"
 
-
-int64_t AvisynthToFFCPUFlags(long AvisynthFlags);
-PixelFormat CSNameToPIXFMT(const char *CSName, PixelFormat Default);
-int ResizerNameToSWSResizer(const char *ResizerName);
-
-#endif
+FFMS_TrackType HaaliTrackTypeToFFTrackType(int TT);
+CodecID MatroskaToFFCodecID(char *Codec, void *CodecPrivate, unsigned int FourCC = 0, unsigned int BitsPerSample = 0);
+const char *GetLAVCSampleFormatName(AVSampleFormat s);
diff --git a/src/core/ffms.cpp b/src/core/ffms.cpp
index 0f4fa55..1715d6d 100644
--- a/src/core/ffms.cpp
+++ b/src/core/ffms.cpp
@@ -370,7 +370,7 @@ static std::string IntToStr(int i, int zp = 0) {
 }
 
 static void ReplaceString(std::string &s, std::string from, std::string to) {
-	int idx;
+	std::string::size_type idx;
 	while ((idx = s.find(from)) != std::string::npos)
 		s.replace(idx, from.length(), to);
 }
diff --git a/src/core/haaliindexer.cpp b/src/core/haaliindexer.cpp
index 48135ef..be8c109 100644
--- a/src/core/haaliindexer.cpp
+++ b/src/core/haaliindexer.cpp
@@ -22,11 +22,12 @@
 
 #include "indexing.h"
 
-
+#include "codectype.h"
 
 FFHaaliIndexer::FFHaaliIndexer(const char *Filename, FFMS_Sources SourceMode) : FFMS_Indexer(Filename) {
 	this->SourceMode = SourceMode;
 	Duration = 0;
+
 	for (int i = 0; i < 32; i++) {
 		TrackType[i] = FFMS_TYPE_UNKNOWN;
 	}
diff --git a/src/core/haalivideo.cpp b/src/core/haalivideo.cpp
index eaa14ff..cb79aca 100644
--- a/src/core/haalivideo.cpp
+++ b/src/core/haalivideo.cpp
@@ -61,7 +61,7 @@ FFHaaliVideo::FFHaaliVideo(const char *SourceFile, int Track,
 		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
 			"Could not open video codec");
 
-#if LIBAVCODEC_VERSION_MAJOR >= 53 || (LIBAVCODEC_VERSION_MAJOR == 52 && LIBAVCODEC_VERSION_MINOR >= 112)
+#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,111,0)
 	CodecContext->thread_count = DecodingThreads;
 #else
 	if (avcodec_thread_init(CodecContext, DecodingThreads))
@@ -79,44 +79,16 @@ FFHaaliVideo::FFHaaliVideo(const char *SourceFile, int Track,
 
 	VP.FPSDenominator = 1;
 	VP.FPSNumerator = 30;
-	VP.RFFDenominator = CodecContext->time_base.num;
-	VP.RFFNumerator = CodecContext->time_base.den;
-	if (CodecContext->codec_id == CODEC_ID_H264) {
-		if (VP.RFFNumerator & 1)
-			VP.RFFDenominator *= 2;
-		else
-			VP.RFFNumerator /= 2;
-	}
-	VP.NumFrames = Frames.size();
-	VP.TopFieldFirst = DecodeFrame->top_field_first;
-	VP.ColorSpace = CodecContext->colorspace;
-	VP.ColorRange = CodecContext->color_range;
-	// these pixfmt's are deprecated but still used
-	if (
-		CodecContext->pix_fmt == PIX_FMT_YUVJ420P
-		|| CodecContext->pix_fmt == PIX_FMT_YUVJ422P
-		|| CodecContext->pix_fmt == PIX_FMT_YUVJ444P
-	)
-		VP.ColorRange = AVCOL_RANGE_JPEG;
-
-	VP.FirstTime = ((Frames.front().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
-	VP.LastTime = ((Frames.back().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
-
-	if (CodecContext->width <= 0 || CodecContext->height <= 0)
-		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
-			"Codec returned zero size video");
 
 	// Calculate the average framerate
 	if (Frames.size() >= 2) {
 		double PTSDiff = (double)(Frames.back().PTS - Frames.front().PTS);
-		VP.FPSDenominator = (unsigned int)(PTSDiff  / (double)1000 / (double)(VP.NumFrames - 1) + 0.5);
+		VP.FPSDenominator = (unsigned int)(PTSDiff  / (double)1000 / (double)(Frames.size() - 1) + 0.5);
 		VP.FPSNumerator = 1000000;
 	}
 
-	// attempt to correct framerate to the proper NTSC fraction, if applicable
-	CorrectNTSCRationalFramerate(&VP.FPSNumerator, &VP.FPSDenominator);
-	// correct the timebase, if necessary
-	CorrectTimebase(&VP, &Frames.TB);
+	// Set the video properties from the codec context
+	SetVideoProperties();
 
 	// Output the already decoded frame so it isn't wasted
 	OutputFrame(DecodeFrame);
@@ -139,7 +111,7 @@ void FFHaaliVideo::DecodeNextFrame(int64_t *AFirstStartTime) {
 	InitNullPacket(Packet);
 
 	if (InitialDecode == -1) {
-		if (DelayCounter > CodecContext->has_b_frames) {
+		if (DelayCounter > FFMS_CALCULATE_DELAY) {
 			DelayCounter--;
 			goto Done;
 		} else {
@@ -184,7 +156,7 @@ void FFHaaliVideo::DecodeNextFrame(int64_t *AFirstStartTime) {
 
 			if (!FrameFinished)
 				DelayCounter++;
-			if (DelayCounter > CodecContext->has_b_frames && !InitialDecode)
+			if (DelayCounter > FFMS_CALCULATE_DELAY && !InitialDecode)
 				goto Done;
 
 			if (FrameFinished)
@@ -193,7 +165,7 @@ void FFHaaliVideo::DecodeNextFrame(int64_t *AFirstStartTime) {
 	}
 
 	// Flush the last frames
-	if (CodecContext->has_b_frames) {
+	if (FFMS_CALCULATE_DELAY) {
 		AVPacket NullPacket;
 		InitNullPacket(NullPacket);
 		avcodec_decode_video2(CodecContext, DecodeFrame, &FrameFinished, &NullPacket);
@@ -227,7 +199,7 @@ ReSeek:
 
 	do {
 		int64_t StartTime;
-		if (CurrentFrame+CodecContext->has_b_frames >= n)
+		if (CurrentFrame + FFMS_CALCULATE_DELAY >= n)
 			CodecContext->skip_frame = AVDISCARD_DEFAULT;
 		else
 			CodecContext->skip_frame = AVDISCARD_NONREF;
diff --git a/src/core/indexing.cpp b/src/core/indexing.cpp
index a7814bf..5ee1537 100644
--- a/src/core/indexing.cpp
+++ b/src/core/indexing.cpp
@@ -20,6 +20,8 @@
 
 #include "indexing.h"
 
+#include "codectype.h"
+
 #include <algorithm>
 #include <fstream>
 #include <iostream>
@@ -434,7 +436,7 @@ void FFMS_Index::ReadIndex(const char *IndexFile) {
 
 	if (IH.Version != FFMS_VERSION)
 		throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
-			std::string("'") + IndexFile + "' is the expected index version");
+			std::string("'") + IndexFile + "' is not the expected index version");
 
 	if (IH.Arch != ARCH)
 		throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
@@ -527,19 +529,19 @@ FFMS_Indexer *FFMS_Indexer::CreateIndexer(const char *Filename, FFMS_Sources Dem
 	if (Demuxer == FFMS_SOURCE_DEFAULT) {
 		// Do matroska indexing instead?
 		if (!strncmp(FormatContext->iformat->name, "matroska", 8)) {
-			av_close_input_file(FormatContext);
+			avformat_close_input(&FormatContext);
 			return new FFMatroskaIndexer(Filename);
 		}
 
 #ifdef HAALISOURCE
 		// Do haali ts indexing instead?
 		if (HasHaaliMPEG && (!strcmp(FormatContext->iformat->name, "mpeg") || !strcmp(FormatContext->iformat->name, "mpegts"))) {
-			av_close_input_file(FormatContext);
+			avformat_close_input(&FormatContext);
 			return new FFHaaliIndexer(Filename, FFMS_SOURCE_HAALIMPEG);
 		}
 
 		if (HasHaaliOGG && !strcmp(FormatContext->iformat->name, "ogg")) {
-			av_close_input_file(FormatContext);
+			avformat_close_input(&FormatContext);
 			return new FFHaaliIndexer(Filename, FFMS_SOURCE_HAALIOGG);
 		}
 #endif
@@ -549,7 +551,7 @@ FFMS_Indexer *FFMS_Indexer::CreateIndexer(const char *Filename, FFMS_Sources Dem
 
 	// someone forced a demuxer, use it
 	if (Demuxer != FFMS_SOURCE_LAVF)
-		av_close_input_file(FormatContext);
+		avformat_close_input(&FormatContext);
 #if !defined(HAALISOURCE)
 	if (Demuxer == FFMS_SOURCE_HAALIOGG || Demuxer == FFMS_SOURCE_HAALIMPEG) {
 		throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_NOT_AVAILABLE, "Your binary was not compiled with support for Haali's DirectShow parsers");
diff --git a/src/core/indexing.h b/src/core/indexing.h
index 183a2fd..6e87bfb 100644
--- a/src/core/indexing.h
+++ b/src/core/indexing.h
@@ -194,6 +194,7 @@ private:
 	FFMS_TrackType TrackType[32];
 	CComQIPtr<IPropertyBag> PropertyBags[32];
 	int64_t Duration;
+	AVFormatContext *FormatContext;
 public:
 	FFHaaliIndexer(const char *Filename, FFMS_Sources SourceMode);
 	FFMS_Index *DoIndexing();
diff --git a/src/core/lavfaudio.cpp b/src/core/lavfaudio.cpp
index ee08be8..28aa59c 100644
--- a/src/core/lavfaudio.cpp
+++ b/src/core/lavfaudio.cpp
@@ -42,7 +42,7 @@ FFLAVFAudio::FFLAVFAudio(const char *SourceFile, int Track, FFMS_Index &Index, i
 				"Could not open audio codec");
 	}
 	catch (...) {
-		av_close_input_file(FormatContext);
+		avformat_close_input(&FormatContext);
 		throw;
 	}
 
@@ -54,7 +54,7 @@ FFLAVFAudio::FFLAVFAudio(const char *SourceFile, int Track, FFMS_Index &Index, i
 }
 
 FFLAVFAudio::~FFLAVFAudio() {
-	av_close_input_file(FormatContext);
+	avformat_close_input(&FormatContext);
 }
 
 void FFLAVFAudio::Seek() {
diff --git a/src/core/lavfindexer.cpp b/src/core/lavfindexer.cpp
index 8cc47d7..51a5245 100644
--- a/src/core/lavfindexer.cpp
+++ b/src/core/lavfindexer.cpp
@@ -29,14 +29,14 @@ FFLAVFIndexer::FFLAVFIndexer(const char *Filename, AVFormatContext *FormatContex
 	this->FormatContext = FormatContext;
 
 	if (avformat_find_stream_info(FormatContext,NULL) < 0) {
-		av_close_input_file(FormatContext);
+		avformat_close_input(&FormatContext);
 		throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
 			"Couldn't find stream information");
 	}
 }
 
 FFLAVFIndexer::~FFLAVFIndexer() {
-	av_close_input_file(FormatContext);
+	avformat_close_input(&FormatContext);
 }
 
 FFMS_Index *FFLAVFIndexer::DoIndexing() {
@@ -90,11 +90,16 @@ FFMS_Index *FFLAVFIndexer::DoIndexing() {
 	std::vector<int64_t> LastValidTS;
 	LastValidTS.resize(FormatContext->nb_streams, ffms_av_nopts_value);
 
+#if (LIBAVFORMAT_VERSION_INT) < (AV_VERSION_INT(52,106,0))
+	int64_t filesize = FormatContext->file_size;
+#else
+	int64_t filesize = avio_size(FormatContext->pb);
+#endif
 	while (av_read_frame(FormatContext, &Packet) >= 0) {
 		// Update progress
 		// FormatContext->pb can apparently be NULL when opening images.
 		if (IC && FormatContext->pb) {
-			if ((*IC)(FormatContext->pb->pos, FormatContext->file_size, ICPrivate))
+			if ((*IC)(FormatContext->pb->pos, filesize, ICPrivate))
 				throw FFMS_Exception(FFMS_ERROR_CANCELLED, FFMS_ERROR_USER,
 					"Cancelled by user");
 		}
diff --git a/src/core/lavfvideo.cpp b/src/core/lavfvideo.cpp
index 2966f78..c7bf0b0 100644
--- a/src/core/lavfvideo.cpp
+++ b/src/core/lavfvideo.cpp
@@ -25,27 +25,26 @@
 void FFLAVFVideo::Free(bool CloseCodec) {
 	if (CloseCodec)
 		avcodec_close(CodecContext);
-	av_close_input_file(FormatContext);
+	avformat_close_input(&FormatContext);
 }
 
 FFLAVFVideo::FFLAVFVideo(const char *SourceFile, int Track, FFMS_Index &Index,
 	int Threads, int SeekMode)
-: Res(FFSourceResources<FFMS_VideoSource>(this))
-, FFMS_VideoSource(SourceFile, Index, Track, Threads)
-, SeekMode(SeekMode)
+: FFMS_VideoSource(SourceFile, Index, Track, Threads)
 , FormatContext(NULL)
+, SeekMode(SeekMode)
+, Res(FFSourceResources<FFMS_VideoSource>(this))
 {
-
 	AVCodec *Codec = NULL;
 
 	LAVFOpenFile(SourceFile, FormatContext);
 
-	if (SeekMode >= 0 && av_seek_frame(FormatContext, VideoTrack, Frames[0].PTS, AVSEEK_FLAG_BACKWARD) < 0)
+	if (SeekMode >= 0 && Frames.size() > 1 && av_seek_frame(FormatContext, VideoTrack, Frames[0].PTS, AVSEEK_FLAG_BACKWARD) < 0)
 		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
 			"Video track is unseekable");
 
 	CodecContext = FormatContext->streams[VideoTrack]->codec;
-#if LIBAVCODEC_VERSION_MAJOR >= 53 || (LIBAVCODEC_VERSION_MAJOR == 52 && LIBAVCODEC_VERSION_MINOR >= 112)
+#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,111,0)
 	CodecContext->thread_count = DecodingThreads;
 #else
 	if (avcodec_thread_init(CodecContext, DecodingThreads))
@@ -70,33 +69,6 @@ FFLAVFVideo::FFLAVFVideo(const char *SourceFile, int Track, FFMS_Index &Index,
 	//VP.image_type = VideoInfo::IT_TFF;
 	VP.FPSDenominator = FormatContext->streams[VideoTrack]->time_base.num;
 	VP.FPSNumerator = FormatContext->streams[VideoTrack]->time_base.den;
-	VP.RFFDenominator = CodecContext->time_base.num;
-	VP.RFFNumerator = CodecContext->time_base.den;
-	if (CodecContext->codec_id == CODEC_ID_H264) {
-		if (VP.RFFNumerator & 1)
-			VP.RFFDenominator *= 2;
-		else
-			VP.RFFNumerator /= 2;
-	}
-	VP.NumFrames = Frames.size();
-	VP.TopFieldFirst = DecodeFrame->top_field_first;
-	VP.ColorSpace = CodecContext->colorspace;
-	VP.ColorRange = CodecContext->color_range;
-	// these pixfmt's are deprecated but still used
-	if (
-		CodecContext->pix_fmt == PIX_FMT_YUVJ420P
-		|| CodecContext->pix_fmt == PIX_FMT_YUVJ422P
-		|| CodecContext->pix_fmt == PIX_FMT_YUVJ444P
-	)
-		VP.ColorRange = AVCOL_RANGE_JPEG;
-
-
-	VP.FirstTime = ((Frames.front().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
-	VP.LastTime = ((Frames.back().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
-
-	if (CodecContext->width <= 0 || CodecContext->height <= 0)
-		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
-			"Codec returned zero size video");
 
 	// sanity check framerate
 	if (VP.FPSDenominator > VP.FPSNumerator || VP.FPSDenominator <= 0 || VP.FPSNumerator <= 0) {
@@ -109,22 +81,16 @@ FFLAVFVideo::FFLAVFVideo(const char *SourceFile, int Track, FFMS_Index &Index,
 		double PTSDiff = (double)(Frames.back().PTS - Frames.front().PTS);
 		double TD = (double)(Frames.TB.Den);
 		double TN = (double)(Frames.TB.Num);
-		VP.FPSDenominator = (unsigned int)(((double)1000000) / (double)((VP.NumFrames - 1) / ((PTSDiff * TN/TD) / (double)1000)));
+		VP.FPSDenominator = (unsigned int)(((double)1000000) / (double)((Frames.size() - 1) / ((PTSDiff * TN/TD) / (double)1000)));
 		VP.FPSNumerator = 1000000;
 	}
 
-	// attempt to correct framerate to the proper NTSC fraction, if applicable
-	CorrectNTSCRationalFramerate(&VP.FPSNumerator, &VP.FPSDenominator);
-	// correct the timebase, if necessary
-	CorrectTimebase(&VP, &Frames.TB);
+	// Set the video properties from the codec context
+	SetVideoProperties();
 
 	// Cannot "output" to PPFrame without doing all other initialization
 	// This is the additional mess required for seekmode=-1 to work in a reasonable way
 	OutputFrame(DecodeFrame);
-
-	// Set AR variables
-	VP.SARNum = CodecContext->sample_aspect_ratio.num;
-	VP.SARDen = CodecContext->sample_aspect_ratio.den;
 }
 
 void FFLAVFVideo::DecodeNextFrame(int64_t *AStartTime) {
@@ -134,7 +100,7 @@ void FFLAVFVideo::DecodeNextFrame(int64_t *AStartTime) {
 	*AStartTime = -1;
 
 	if (InitialDecode == -1) {
-		if (DelayCounter > CodecContext->has_b_frames) {
+		if (DelayCounter > FFMS_CALCULATE_DELAY) {
 			DelayCounter--;
 			goto Done;
 		} else {
@@ -155,7 +121,7 @@ void FFLAVFVideo::DecodeNextFrame(int64_t *AStartTime) {
 
 			if (!FrameFinished)
 				DelayCounter++;
-			if (DelayCounter > CodecContext->has_b_frames && !InitialDecode) {
+			if (DelayCounter > FFMS_CALCULATE_DELAY && !InitialDecode) {
 				av_free_packet(&Packet);
 				goto Done;
 			}
@@ -168,7 +134,7 @@ void FFLAVFVideo::DecodeNextFrame(int64_t *AStartTime) {
 	}
 
 	// Flush the last frames
-	if (CodecContext->has_b_frames) {
+	if (FFMS_CALCULATE_DELAY) {
 		AVPacket NullPacket;
 		InitNullPacket(NullPacket);
 		avcodec_decode_video2(CodecContext, DecodeFrame, &FrameFinished, &NullPacket);
@@ -223,7 +189,7 @@ ReSeek:
 
 	do {
 		int64_t StartTime;
-		if (CurrentFrame+CodecContext->has_b_frames >= n)
+		if (CurrentFrame + FFMS_CALCULATE_DELAY >= n)
 			CodecContext->skip_frame = AVDISCARD_DEFAULT;
 		else
 			CodecContext->skip_frame = AVDISCARD_NONREF;
diff --git a/src/core/matroskaaudio.cpp b/src/core/matroskaaudio.cpp
index d324316..6e295aa 100644
--- a/src/core/matroskaaudio.cpp
+++ b/src/core/matroskaaudio.cpp
@@ -19,6 +19,7 @@
 //  THE SOFTWARE.
 
 #include "audiosource.h"
+#include "codectype.h"
 #include <cassert>
 
 FFMatroskaAudio::FFMatroskaAudio(const char *SourceFile, int Track, FFMS_Index &Index, int DelayMode)
diff --git a/src/core/matroskaindexer.cpp b/src/core/matroskaindexer.cpp
index b17d490..b90a4f9 100644
--- a/src/core/matroskaindexer.cpp
+++ b/src/core/matroskaindexer.cpp
@@ -19,12 +19,14 @@
 //  THE SOFTWARE.
 
 #include "indexing.h"
-#include "matroskaparser.h"
 
+#include "codectype.h"
+#include "matroskaparser.h"
 
 
 FFMatroskaIndexer::FFMatroskaIndexer(const char *Filename) : FFMS_Indexer(Filename) {
 	char ErrorMessage[256];
+
 	for (int i = 0; i < 32; i++) {
 		Codec[i] = NULL;
 	}
@@ -118,7 +120,7 @@ FFMS_Index *FFMatroskaIndexer::DoIndexing() {
 		unsigned char TrackType = mkv_GetTrackInfo(MF, Track)->Type;
 
 		TrackCompressionContext *TCC = NULL;
-		if (VideoContexts[Track].Parser || TrackType == TT_AUDIO && (IndexMask & (1 << Track))) {
+		if (VideoContexts[Track].Parser || (TrackType == TT_AUDIO && (IndexMask & (1 << Track)))) {
 			if (TrackType == TT_VIDEO)
 				TCC = VideoContexts[Track].TCC;
 			else
diff --git a/src/core/matroskavideo.cpp b/src/core/matroskavideo.cpp
index 5ff3a6d..02230e2 100644
--- a/src/core/matroskavideo.cpp
+++ b/src/core/matroskavideo.cpp
@@ -20,11 +20,10 @@
 
 #include "videosource.h"
 
-
+#include "codectype.h"
 
 void FFMatroskaVideo::Free(bool CloseCodec) {
-	if (TCC)
-		delete TCC;
+	TCC.reset();
 	if (MC.ST.fp) {
 		mkv_Close(MF);
 	}
@@ -35,12 +34,13 @@ void FFMatroskaVideo::Free(bool CloseCodec) {
 
 FFMatroskaVideo::FFMatroskaVideo(const char *SourceFile, int Track,
 	FFMS_Index &Index, int Threads)
-	: Res(FFSourceResources<FFMS_VideoSource>(this)), FFMS_VideoSource(SourceFile, Index, Track, Threads) {
-
+: FFMS_VideoSource(SourceFile, Index, Track, Threads)
+, MF(0)
+, Res(FFSourceResources<FFMS_VideoSource>(this))
+, PacketNumber(0)
+{
 	AVCodec *Codec = NULL;
 	TrackInfo *TI = NULL;
-	TCC = NULL;
-	PacketNumber = 0;
 
 	MC.ST.fp = ffms_fopen(SourceFile, "rb");
 	if (MC.ST.fp == NULL) {
@@ -61,10 +61,10 @@ FFMatroskaVideo::FFMatroskaVideo(const char *SourceFile, int Track,
 	TI = mkv_GetTrackInfo(MF, VideoTrack);
 
 	if (TI->CompEnabled)
-		TCC = new TrackCompressionContext(MF, TI, VideoTrack);
+		TCC.reset(new TrackCompressionContext(MF, TI, VideoTrack));
 
 	CodecContext = avcodec_alloc_context3(NULL);
-#if LIBAVCODEC_VERSION_MAJOR >= 53 || (LIBAVCODEC_VERSION_MAJOR == 52 && LIBAVCODEC_VERSION_MINOR >= 112)
+#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,111,0)
 	CodecContext->thread_count = DecodingThreads;
 #else
 	if (avcodec_thread_init(CodecContext, DecodingThreads))
@@ -89,44 +89,16 @@ FFMatroskaVideo::FFMatroskaVideo(const char *SourceFile, int Track,
 
 	VP.FPSDenominator = 1;
 	VP.FPSNumerator = 30;
-	VP.RFFDenominator = CodecContext->time_base.num;
-	VP.RFFNumerator = CodecContext->time_base.den;
-	if (CodecContext->codec_id == CODEC_ID_H264) {
-		if (VP.RFFNumerator & 1)
-			VP.RFFDenominator *= 2;
-		else
-			VP.RFFNumerator /= 2;
-	}
-	VP.NumFrames = Frames.size();
-	VP.TopFieldFirst = DecodeFrame->top_field_first;
-	VP.ColorSpace = CodecContext->colorspace;
-	VP.ColorRange = CodecContext->color_range;
-	// these pixfmt's are deprecated but still used
-	if (
-		CodecContext->pix_fmt == PIX_FMT_YUVJ420P
-		|| CodecContext->pix_fmt == PIX_FMT_YUVJ422P
-		|| CodecContext->pix_fmt == PIX_FMT_YUVJ444P
-	)
-		VP.ColorRange = AVCOL_RANGE_JPEG;
-
-	VP.FirstTime = ((Frames.front().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
-	VP.LastTime = ((Frames.back().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
-
-	if (CodecContext->width <= 0 || CodecContext->height <= 0)
-		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
-			"Codec returned zero size video");
 
 	// Calculate the average framerate
 	if (Frames.size() >= 2) {
 		double PTSDiff = (double)(Frames.back().PTS - Frames.front().PTS);
-		VP.FPSDenominator = (unsigned int)(PTSDiff * mkv_TruncFloat(TI->TimecodeScale) / (double)1000 / (double)(VP.NumFrames - 1) + 0.5);
+		VP.FPSDenominator = (unsigned int)(PTSDiff * mkv_TruncFloat(TI->TimecodeScale) / (double)1000 / (double)(Frames.size() - 1) + 0.5);
 		VP.FPSNumerator = 1000000;
 	}
 
-	// attempt to correct framerate to the proper NTSC fraction, if applicable
-	CorrectNTSCRationalFramerate(&VP.FPSNumerator, &VP.FPSDenominator);
-	// correct the timebase, if necessary
-	CorrectTimebase(&VP, &Frames.TB);
+	// Set the video properties from the codec context
+	SetVideoProperties();
 
 	// Output the already decoded frame so it isn't wasted
 	OutputFrame(DecodeFrame);
@@ -150,7 +122,7 @@ void FFMatroskaVideo::DecodeNextFrame() {
 	unsigned int FrameSize;
 
 	if (InitialDecode == -1) {
-		if (DelayCounter > CodecContext->has_b_frames) {
+		if (DelayCounter > FFMS_CALCULATE_DELAY) {
 			DelayCounter--;
 			goto Done;
 		} else {
@@ -160,11 +132,11 @@ void FFMatroskaVideo::DecodeNextFrame() {
 
 	while (PacketNumber < Frames.size()) {
 		// The additional indirection is because the packets are stored in
-		// presentation order and not decoding order, this is unnoticable
+		// presentation order and not decoding order, this is unnoticeable
 		// in the other sources where less is done manually
 		const TFrameInfo &FI = Frames[Frames[PacketNumber].OriginalPos];
 		FrameSize = FI.FrameSize;
-		ReadFrame(FI.FilePos, FrameSize, TCC, MC);
+		ReadFrame(FI.FilePos, FrameSize, TCC.get(), MC);
 
 		Packet.data = MC.Buffer;
 		Packet.size = FrameSize;
@@ -179,7 +151,7 @@ void FFMatroskaVideo::DecodeNextFrame() {
 
 		if (!FrameFinished)
 			DelayCounter++;
-		if (DelayCounter > CodecContext->has_b_frames && !InitialDecode)
+		if (DelayCounter > FFMS_CALCULATE_DELAY && !InitialDecode)
 			goto Done;
 
 		if (FrameFinished)
@@ -187,7 +159,7 @@ void FFMatroskaVideo::DecodeNextFrame() {
 	}
 
 	// Flush the last frames
-	if (CodecContext->has_b_frames) {
+	if (FFMS_CALCULATE_DELAY) {
 		AVPacket NullPacket;
 		InitNullPacket(NullPacket);
 		avcodec_decode_video2(CodecContext, DecodeFrame, &FrameFinished, &NullPacket);
@@ -217,7 +189,7 @@ FFMS_Frame *FFMatroskaVideo::GetFrame(int n) {
 	}
 
 	do {
-		if (CurrentFrame+CodecContext->has_b_frames >= n)
+		if (CurrentFrame + FFMS_CALCULATE_DELAY >= n)
 			CodecContext->skip_frame = AVDISCARD_DEFAULT;
 		else
 			CodecContext->skip_frame = AVDISCARD_NONREF;
diff --git a/src/core/numthreads.cpp b/src/core/numthreads.cpp
index 92d1b63..11ddd65 100644
--- a/src/core/numthreads.cpp
+++ b/src/core/numthreads.cpp
@@ -18,7 +18,10 @@
 //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 //  THE SOFTWARE.
 
+#ifndef _GNU_SOURCE
 #define _GNU_SOURCE
+#endif
+
 #define MAX_NUM_THREADS 16 //libav currently has bugs with > 16 threads
 #include "numthreads.h"
 
@@ -26,6 +29,9 @@
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
 #endif
+#ifdef __CYGWIN__
+#include <sys/unistd.h>
+#endif
 #ifdef __LINUX__
 #include <sched.h>
 #endif
diff --git a/src/core/utils.cpp b/src/core/utils.cpp
index fcbe21c..441cf71 100644
--- a/src/core/utils.cpp
+++ b/src/core/utils.cpp
@@ -21,7 +21,10 @@
 #include <string.h>
 #include <errno.h>
 #include <algorithm>
+
 #include "utils.h"
+
+#include "codectype.h"
 #include "indexing.h"
 
 #ifdef _WIN32
@@ -34,29 +37,12 @@ extern "C" {
 }
 #endif // _WIN32
 
-
-// Export the array but not its data type... fun...
-typedef struct CodecTags{
-    char str[20];
-    CodecID id;
-} CodecTags;
-
-extern "C" {
-extern const AVCodecTag ff_codec_bmp_tags[];
-extern const CodecTags ff_mkv_codec_tags[];
-extern const AVCodecTag ff_codec_movvideo_tags[];
-extern const AVCodecTag ff_codec_wav_tags[];
-}
-
-
 extern bool GlobalUseUTF8Paths;
 
-
-
-FFMS_Exception::FFMS_Exception(int ErrorType, int SubType, const char *Message) : _ErrorType(ErrorType), _SubType(SubType), _Message(Message) {
+FFMS_Exception::FFMS_Exception(int ErrorType, int SubType, const char *Message) : _Message(Message), _ErrorType(ErrorType), _SubType(SubType) {
 }
 
-FFMS_Exception::FFMS_Exception(int ErrorType, int SubType, const std::string &Message) : _ErrorType(ErrorType), _SubType(SubType), _Message(Message) {
+FFMS_Exception::FFMS_Exception(int ErrorType, int SubType, const std::string &Message) : _Message(Message), _ErrorType(ErrorType), _SubType(SubType) {
 }
 
 FFMS_Exception::~FFMS_Exception() throw () {
@@ -118,26 +104,6 @@ void ClearErrorInfo(FFMS_ErrorInfo *ErrorInfo) {
 	}
 }
 
-FFMS_TrackType HaaliTrackTypeToFFTrackType(int TT) {
-	switch (TT) {
-		case TT_VIDEO: return FFMS_TYPE_VIDEO; break;
-		case TT_AUDIO: return FFMS_TYPE_AUDIO; break;
-		case TT_SUB: return FFMS_TYPE_SUBTITLE; break;
-		default: return FFMS_TYPE_UNKNOWN;
-	}
-}
-
-const char *GetLAVCSampleFormatName(AVSampleFormat s) {
-	switch (s) {
-		case AV_SAMPLE_FMT_U8:	return "8-bit unsigned integer";
-		case AV_SAMPLE_FMT_S16:	return "16-bit signed integer";
-		case AV_SAMPLE_FMT_S32:	return "32-bit signed integer";
-		case AV_SAMPLE_FMT_FLT:	return "Single-precision floating point";
-		case AV_SAMPLE_FMT_DBL:	return "Double-precision floating point";
-		default:				return "Unknown";
-	}
-}
-
 template<class T> static void safe_aligned_reallocz(T *&ptr, size_t old_size, size_t new_size) {
 	void *newalloc = av_mallocz(new_size);
 	if (newalloc) {
@@ -251,9 +217,6 @@ void InitNullPacket(AVPacket &pkt) {
 void FillAP(FFMS_AudioProperties &AP, AVCodecContext *CTX, FFMS_Track &Frames) {
 	AP.SampleFormat = static_cast<FFMS_SampleFormat>(CTX->sample_fmt);
 	AP.BitsPerSample = av_get_bits_per_sample_fmt(CTX->sample_fmt);
-	if (CTX->sample_fmt == AV_SAMPLE_FMT_S32 && CTX->bits_per_raw_sample)
-		AP.BitsPerSample = CTX->bits_per_raw_sample;
-
 	AP.Channels = CTX->channels;;
 	AP.ChannelLayout = CTX->channel_layout;
 	AP.SampleRate = CTX->sample_rate;
@@ -289,68 +252,37 @@ void vtCopy(VARIANT& vt,void *dest) {
 
 #endif
 
-CodecID MatroskaToFFCodecID(char *Codec, void *CodecPrivate, unsigned int FourCC, unsigned int BitsPerSample) {
-/* Look up native codecs */
-	for(int i = 0; ff_mkv_codec_tags[i].id != CODEC_ID_NONE; i++){
-		if(!strncmp(ff_mkv_codec_tags[i].str, Codec,
-			strlen(ff_mkv_codec_tags[i].str))) {
-
-				// Uncompressed and exotic format fixup
-				// This list is incomplete
-				CodecID CID = ff_mkv_codec_tags[i].id;
-				switch (CID) {
-					case CODEC_ID_PCM_S16LE:
-						switch (BitsPerSample) {
-							case 8: CID = CODEC_ID_PCM_S8; break;
-							case 16: CID = CODEC_ID_PCM_S16LE; break;
-							case 24: CID = CODEC_ID_PCM_S24LE; break;
-							case 32: CID = CODEC_ID_PCM_S32LE; break;
-						}
-						break;
-					case CODEC_ID_PCM_S16BE:
-						switch (BitsPerSample) {
-							case 8: CID = CODEC_ID_PCM_S8; break;
-							case 16: CID = CODEC_ID_PCM_S16BE; break;
-							case 24: CID = CODEC_ID_PCM_S24BE; break;
-							case 32: CID = CODEC_ID_PCM_S32BE; break;
-						}
-						break;
-					default:
-						break;
-				}
-
-				return CID;
-			}
-	}
-
-/* Video codecs for "avi in mkv" mode */
-	const AVCodecTag *const tags[] = { ff_codec_bmp_tags, 0 };
-
-	if (!strcmp(Codec, "V_MS/VFW/FOURCC")) {
-		FFMS_BITMAPINFOHEADER *b = reinterpret_cast<FFMS_BITMAPINFOHEADER *>(CodecPrivate);
-		return av_codec_get_id(tags, b->biCompression);
+void InitializeCodecContextFromMatroskaTrackInfo(TrackInfo *TI, AVCodecContext *CodecContext) {
+	uint8_t *PrivateDataSrc = static_cast<uint8_t *>(TI->CodecPrivate);
+	size_t PrivateDataSize = TI->CodecPrivateSize;
+	size_t BIHSize = sizeof(FFMS_BITMAPINFOHEADER); // 40 bytes
+	if (!strncmp(TI->CodecID, "V_MS/VFW/FOURCC", 15) && PrivateDataSize >= BIHSize) {
+		// For some reason UTVideo requires CodecContext->codec_tag (i.e. the FourCC) to be set.
+		// Fine, it can't hurt to set it, so let's go find it.
+		// In a V_MS/VFW/FOURCC track, the codecprivate starts with a BITMAPINFOHEADER. If you treat that struct
+		// as an array of uint32_t, the biCompression member (that's the FourCC) can be found at offset 4.
+		// Therefore the following derp.
+		CodecContext->codec_tag = reinterpret_cast<uint32_t *>(PrivateDataSrc)[4];
+
+		// Now skip copying the BITMAPINFOHEADER into the extradata, because lavc doesn't expect it to be there.
+		if (PrivateDataSize <= BIHSize) {
+			PrivateDataSrc = NULL;
+			PrivateDataSize = 0;
+		}
+		else {
+			PrivateDataSrc += BIHSize;
+			PrivateDataSize -= BIHSize;
+		}
 	}
-
-	if (!strcmp(Codec, "V_FOURCC")) {
-		return av_codec_get_id(tags, FourCC);
+	// I think you might need to do some special handling for A_MS/ACM extradata too,
+	// but I don't think anyone actually uses that.
+	
+	if (PrivateDataSrc && PrivateDataSize > 0) {
+		CodecContext->extradata = static_cast<uint8_t *>(av_mallocz(PrivateDataSize + FF_INPUT_BUFFER_PADDING_SIZE));
+		CodecContext->extradata_size = PrivateDataSize;
+		memcpy(CodecContext->extradata, PrivateDataSrc, PrivateDataSize);
 	}
 
-// FIXME
-/* Audio codecs for "acm in mkv" mode */
-		//#include "Mmreg.h"
-		//((WAVEFORMATEX *)TI->CodecPrivate)->wFormatTag
-
-/* Fixup for uncompressed video formats */
-
-/* Fixup for uncompressed audio formats */
-
-	return CODEC_ID_NONE;
-}
-
-void InitializeCodecContextFromMatroskaTrackInfo(TrackInfo *TI, AVCodecContext *CodecContext) {
-	CodecContext->extradata = static_cast<uint8_t *>(TI->CodecPrivate);
-	CodecContext->extradata_size = TI->CodecPrivateSize;
-
 	if (TI->Type == TT_VIDEO) {
 		CodecContext->coded_width = TI->AV.Video.PixelWidth;
 		CodecContext->coded_height = TI->AV.Video.PixelHeight;
@@ -386,38 +318,18 @@ FFCodecContext InitializeCodecContextFromHaaliInfo(CComQIPtr<IPropertyBag> pBag)
 		if (SUCCEEDED(pBag->Read(L"FOURCC", &pV, NULL)) && SUCCEEDED(pV.ChangeType(VT_UI4)))
 			FourCC = pV.uintVal;
 
-		FFMS_BITMAPINFOHEADER bih;
-		memset(&bih, 0, sizeof bih);
-		if (FourCC) {
-			// Reconstruct the missing codec private part for VC1
-			bih.biSize = sizeof bih;
-			bih.biCompression = FourCC;
-			bih.biBitCount = 24;
-			bih.biPlanes = 1;
-			bih.biHeight = CodecContext->coded_height;
-		}
-
 		pV.Clear();
 		if (SUCCEEDED(pBag->Read(L"CodecPrivate", &pV, NULL))) {
-			bih.biSize += vtSize(pV);
-			CodecContext->extradata = static_cast<uint8_t*>(av_malloc(bih.biSize));
-			// prepend BITMAPINFOHEADER if there's anything interesting in it (i.e. we're decoding VC1)
-			if (FourCC)
-				memcpy(CodecContext->extradata, &bih, sizeof bih);
-			vtCopy(pV, CodecContext->extradata + (FourCC ? sizeof bih : 0));
-		}
-		// use the BITMAPINFOHEADER only. not sure if this is correct or if it's ever going to be used...
-		else {
-			CodecContext->extradata = static_cast<uint8_t*>(av_malloc(bih.biSize));
-			memcpy(CodecContext->extradata, &bih, sizeof bih);
+			CodecContext->extradata_size = vtSize(pV);
+			CodecContext->extradata = static_cast<uint8_t*>(av_mallocz(CodecContext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE));
+			vtCopy(pV, CodecContext->extradata);
 		}
-		CodecContext->extradata_size = bih.biSize;
 	}
 	else if (TT == TT_AUDIO) {
 		pV.Clear();
 		if (SUCCEEDED(pBag->Read(L"CodecPrivate", &pV, NULL))) {
 			CodecContext->extradata_size = vtSize(pV);
-			CodecContext->extradata = static_cast<uint8_t*>(av_malloc(CodecContext->extradata_size));
+			CodecContext->extradata = static_cast<uint8_t*>(av_mallocz(CodecContext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE));
 			vtCopy(pV, CodecContext->extradata);
 		}
 
@@ -633,12 +545,9 @@ void LAVFOpenFile(const char *SourceFile, AVFormatContext *&FormatContext) {
 			std::string("Couldn't open '") + SourceFile + "'");
 
 	if (avformat_find_stream_info(FormatContext,NULL) < 0) {
-		av_close_input_file(FormatContext);
+		avformat_close_input(&FormatContext);
 		FormatContext = NULL;
 		throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
 			"Couldn't find stream information");
 	}
 }
-
-
-
diff --git a/src/core/utils.h b/src/core/utils.h
index 3c8f8e2..18859d5 100644
--- a/src/core/utils.h
+++ b/src/core/utils.h
@@ -174,7 +174,7 @@ class AlignedBuffer {
 	T *buf;
 
 public:
-	AlignedBuffer(size_t n = 1, bool zero = false) {
+	explicit AlignedBuffer(size_t n = 1) {
 		buf = (T*) av_malloc(sizeof(*buf) * n);
 		if (!buf) throw std::bad_alloc();
 	}
@@ -202,7 +202,6 @@ public:
 
 
 void ClearErrorInfo(FFMS_ErrorInfo *ErrorInfo);
-FFMS_TrackType HaaliTrackTypeToFFTrackType(int TT);
 void ReadFrame(uint64_t FilePos, unsigned int &FrameSize, TrackCompressionContext *TCC, MatroskaReaderContext &Context);
 bool AudioFMTIsFloat(AVSampleFormat FMT);
 void InitNullPacket(AVPacket &pkt);
@@ -215,7 +214,6 @@ FFCodecContext InitializeCodecContextFromHaaliInfo(CComQIPtr<IPropertyBag> pBag)
 #endif
 
 void InitializeCodecContextFromMatroskaTrackInfo(TrackInfo *TI, AVCodecContext *CodecContext);
-CodecID MatroskaToFFCodecID(char *Codec, void *CodecPrivate, unsigned int FourCC = 0, unsigned int BitsPerSample = 0);
 FILE *ffms_fopen(const char *filename, const char *mode);
 size_t ffms_mbstowcs (wchar_t *wcstr, const char *mbstr, size_t max);
 #if defined(_WIN32) && LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53,0,3)
@@ -225,7 +223,6 @@ void ffms_patch_lavf_file_open();
 CComPtr<IMMContainer> HaaliOpenFile(const char *SourceFile, FFMS_Sources SourceMode);
 #endif // HAALISOURCE
 void LAVFOpenFile(const char *SourceFile, AVFormatContext *&FormatContext);
-const char *GetLAVCSampleFormatName(AVSampleFormat s);
 
 
 #endif
diff --git a/src/core/videosource.cpp b/src/core/videosource.cpp
index c5a0bbb..e6fe3b9 100644
--- a/src/core/videosource.cpp
+++ b/src/core/videosource.cpp
@@ -185,6 +185,8 @@ FFMS_Frame *FFMS_VideoSource::OutputFrame(AVFrame *Frame) {
 	LocalFrame.RepeatPict = Frame->repeat_pict;
 	LocalFrame.InterlacedFrame = Frame->interlaced_frame;
 	LocalFrame.TopFieldFirst = Frame->top_field_first;
+	LocalFrame.ColorSpace = OutputColorSpace;
+	LocalFrame.ColorRange = OutputColorRange;
 
 	LastFrameHeight = CodecContext->height;
 	LastFrameWidth = CodecContext->width;
@@ -195,7 +197,6 @@ FFMS_Frame *FFMS_VideoSource::OutputFrame(AVFrame *Frame) {
 
 FFMS_VideoSource::FFMS_VideoSource(const char *SourceFile, FFMS_Index &Index, int Track, int Threads)
 : Index(Index)
-, Frames(Index[0]) // dummy initialization
 , CodecContext(NULL)
 {
 	if (Track < 0 || Track >= static_cast<int>(Index.size()))
@@ -235,6 +236,8 @@ FFMS_VideoSource::FFMS_VideoSource(const char *SourceFile, FFMS_Index &Index, in
 	TargetWidth = -1;
 	TargetResizer = 0;
 	OutputFormat = PIX_FMT_NONE;
+	OutputColorSpace = AVCOL_SPC_UNSPECIFIED;
+	OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
 	if (Threads < 1)
 		DecodingThreads = GetNumberOfLogicalCPUs();
 	else
@@ -288,6 +291,17 @@ void FFMS_VideoSource::SetOutputFormat(const PixelFormat *TargetFormats, int Wid
 	OutputFrame(DecodeFrame);
 }
 
+static int handle_jpeg(PixelFormat *format)
+{
+	switch (*format) {
+		case PIX_FMT_YUVJ420P: *format = PIX_FMT_YUV420P; return AVCOL_RANGE_JPEG;
+		case PIX_FMT_YUVJ422P: *format = PIX_FMT_YUV422P; return AVCOL_RANGE_JPEG;
+		case PIX_FMT_YUVJ444P: *format = PIX_FMT_YUV444P; return AVCOL_RANGE_JPEG;
+		case PIX_FMT_YUVJ440P: *format = PIX_FMT_YUV440P; return AVCOL_RANGE_JPEG;
+		default:                                          return AVCOL_RANGE_UNSPECIFIED;
+	}
+}
+
 void FFMS_VideoSource::ReAdjustOutputFormat() {
 	if (SWS) {
 		sws_freeContext(SWS);
@@ -302,11 +316,28 @@ void FFMS_VideoSource::ReAdjustOutputFormat() {
 			"No suitable output format found");
 	}
 
-	if (CodecContext->pix_fmt != OutputFormat || TargetWidth != CodecContext->width || TargetHeight != CodecContext->height) {
+	PixelFormat InputFormat = CodecContext->pix_fmt;
+	int ColorRange = handle_jpeg(&InputFormat);
+	if (ColorRange == AVCOL_RANGE_UNSPECIFIED) {
+		if (CodecContext->color_range == AVCOL_RANGE_UNSPECIFIED) {
+			OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
+			ColorRange = AVCOL_RANGE_MPEG; // assumption
+		}
+		else {
+			OutputColorRange = CodecContext->color_range;
+			ColorRange = CodecContext->color_range;
+		}
+	}
+
+	if (InputFormat != OutputFormat || TargetWidth != CodecContext->width || TargetHeight != CodecContext->height) {
 		int ColorSpace = CodecContext->colorspace;
-		if (ColorSpace == AVCOL_SPC_UNSPECIFIED) ColorSpace = -1;
+		if (ColorSpace == AVCOL_SPC_UNSPECIFIED) {
+			ColorSpace = GetSwsAssumedColorSpace(CodecContext->width, CodecContext->height);
+			OutputColorSpace = (AVColorSpace)ColorSpace;
+		}
+		
 		SWS = GetSwsContext(CodecContext->width, CodecContext->height, CodecContext->pix_fmt, TargetWidth, TargetHeight,
-			OutputFormat, GetSWSCPUFlags() | TargetResizer, ColorSpace);
+			OutputFormat, GetSWSCPUFlags() | TargetResizer, ColorSpace, ColorRange);
 		if (SWS == NULL) {
 			ResetOutputFormat();
 			throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_INVALID_ARGUMENT,
@@ -331,3 +362,42 @@ void FFMS_VideoSource::ResetOutputFormat() {
 	
 	OutputFrame(DecodeFrame);
 }
+
+void FFMS_VideoSource::SetVideoProperties() {
+	VP.RFFDenominator = CodecContext->time_base.num;
+	VP.RFFNumerator = CodecContext->time_base.den;
+	if (CodecContext->codec_id == CODEC_ID_H264) {
+		if (VP.RFFNumerator & 1)
+			VP.RFFDenominator *= 2;
+		else
+			VP.RFFNumerator /= 2;
+	}
+	VP.NumFrames = Frames.size();
+	VP.TopFieldFirst = DecodeFrame->top_field_first;
+	VP.ColorSpace = CodecContext->colorspace;
+	VP.ColorRange = CodecContext->color_range;
+	// these pixfmt's are deprecated but still used
+	if (
+		CodecContext->pix_fmt == PIX_FMT_YUVJ420P
+		|| CodecContext->pix_fmt == PIX_FMT_YUVJ422P
+		|| CodecContext->pix_fmt == PIX_FMT_YUVJ444P
+		)
+		VP.ColorRange = AVCOL_RANGE_JPEG;
+
+
+	VP.FirstTime = ((Frames.front().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
+	VP.LastTime = ((Frames.back().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
+
+	if (CodecContext->width <= 0 || CodecContext->height <= 0)
+		throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
+		"Codec returned zero size video");
+
+	// attempt to correct framerate to the proper NTSC fraction, if applicable
+	CorrectNTSCRationalFramerate(&VP.FPSNumerator, &VP.FPSDenominator);
+	// correct the timebase, if necessary
+	CorrectTimebase(&VP, &Frames.TB);
+
+	// Set AR variables
+	VP.SARNum = CodecContext->sample_aspect_ratio.num;
+	VP.SARDen = CodecContext->sample_aspect_ratio.den;
+}
diff --git a/src/core/videosource.h b/src/core/videosource.h
index 0c2760d..bcbed79 100644
--- a/src/core/videosource.h
+++ b/src/core/videosource.h
@@ -30,16 +30,16 @@ extern "C" {
 #endif // FFMS_USE_POSTPROC
 }
 
-// must be included after ffmpeg headers
-#include "ffmscompat.h"
-
-#include <vector>
 #include <algorithm>
+#include <memory>
 #include <sstream>
+#include <vector>
+
+#include "ffms.h"
+#include "ffmscompat.h"
 #include "indexing.h"
 #include "utils.h"
 #include "videoutils.h"
-#include "ffms.h"
 
 #ifdef HAALISOURCE
 #	define WIN32_LEAN_AND_MEAN
@@ -69,6 +69,8 @@ private:
 	std::vector<PixelFormat> TargetPixelFormats;
 	int TargetResizer;
 	PixelFormat OutputFormat;
+	AVColorRange OutputColorRange;
+	AVColorSpace OutputColorSpace;
 	AVPicture PPFrame;
 	AVPicture SWSFrame;
 protected:
@@ -77,7 +79,7 @@ protected:
 	AVFrame *DecodeFrame;
 	int LastFrameNum;
 	FFMS_Index &Index;
-	FFMS_Track &Frames;
+	FFMS_Track Frames;
 	int VideoTrack;
 	int	CurrentFrame;
 	int DelayCounter;
@@ -90,6 +92,7 @@ protected:
 	void ReAdjustOutputFormat();
 	FFMS_Frame *OutputFrame(AVFrame *Frame);
 	virtual void Free(bool CloseCodec) = 0;
+	void SetVideoProperties();
 public:
 	virtual ~FFMS_VideoSource();
 	const FFMS_VideoProperties& GetVideoProperties() { return VP; }
@@ -121,7 +124,7 @@ class FFMatroskaVideo : public FFMS_VideoSource {
 private:
 	MatroskaFile *MF;
 	MatroskaReaderContext MC;
-	TrackCompressionContext *TCC;
+	std::auto_ptr<TrackCompressionContext> TCC;
 	char ErrorMessage[256];
 	FFSourceResources<FFMS_VideoSource> Res;
 	size_t PacketNumber;
diff --git a/src/core/videoutils.cpp b/src/core/videoutils.cpp
index 594019d..c7581aa 100644
--- a/src/core/videoutils.cpp
+++ b/src/core/videoutils.cpp
@@ -22,6 +22,7 @@
 #include "videoutils.h"
 
 #include <algorithm>
+#include <math.h>
 
 /* if you have this, we'll assume you have a new enough libavutil too */
 #if LIBSWSCALE_VERSION_INT >= AV_VERSION_INT(0, 12, 0)
@@ -31,6 +32,7 @@ extern "C" {
 #endif
 
 
+
 // hack
 extern int CPUFeatures;
 
@@ -65,18 +67,7 @@ int64_t GetSWSCPUFlags() {
 	return Flags;
 }
 
-static int handle_jpeg(PixelFormat *format)
-{
-	switch (*format) {
-	case PIX_FMT_YUVJ420P: *format = PIX_FMT_YUV420P; return 1;
-	case PIX_FMT_YUVJ422P: *format = PIX_FMT_YUV422P; return 1;
-	case PIX_FMT_YUVJ444P: *format = PIX_FMT_YUV444P; return 1;
-	case PIX_FMT_YUVJ440P: *format = PIX_FMT_YUV440P; return 1;
-	default:                                          return 0;
-	}
-}
-
-SwsContext *GetSwsContext(int SrcW, int SrcH, PixelFormat SrcFormat, int DstW, int DstH, PixelFormat DstFormat, int64_t Flags, int ColorSpace) {
+SwsContext *GetSwsContext(int SrcW, int SrcH, PixelFormat SrcFormat, int DstW, int DstH, PixelFormat DstFormat, int64_t Flags, int ColorSpace, int ColorRange) {
 	Flags |= SWS_FULL_CHR_H_INT | SWS_FULL_CHR_H_INP;
 #if LIBSWSCALE_VERSION_INT < AV_VERSION_INT(0, 12, 0)
 	return sws_getContext(SrcW, SrcH, SrcFormat, DstW, DstH, DstFormat, Flags, 0, 0, 0);
@@ -84,23 +75,24 @@ SwsContext *GetSwsContext(int SrcW, int SrcH, PixelFormat SrcFormat, int DstW, i
 	SwsContext *Context = sws_alloc_context();
 	if (!Context) return 0;
 
-	if (ColorSpace == -1)
-		ColorSpace = (SrcW > 1024 || SrcH >= 600) ? SWS_CS_ITU709 : SWS_CS_DEFAULT;
-
-	int SrcRange = handle_jpeg(&SrcFormat);
-	int DstRange = handle_jpeg(&DstFormat);
+	// The intention here is to never change the color range.
+	int Range; // 0 = limited range, 1 = full range
+	if (ColorRange == AVCOL_RANGE_JPEG)
+		Range = 1;
+	else // explicit limited range, or unspecified
+		Range = 0;
 
 	av_set_int(Context, "sws_flags", Flags);
 	av_set_int(Context, "srcw",       SrcW);
 	av_set_int(Context, "srch",       SrcH);
 	av_set_int(Context, "dstw",       DstW);
 	av_set_int(Context, "dsth",       DstH);
-	av_set_int(Context, "src_range",  SrcRange);
-	av_set_int(Context, "dst_range",  DstRange);
+	av_set_int(Context, "src_range",  Range);
+	av_set_int(Context, "dst_range",  Range);
 	av_set_int(Context, "src_format", SrcFormat);
 	av_set_int(Context, "dst_format", DstFormat);
 
-	sws_setColorspaceDetails(Context, sws_getCoefficients(ColorSpace), SrcRange, sws_getCoefficients(ColorSpace), DstRange, 0, 1<<16, 1<<16);
+	sws_setColorspaceDetails(Context, sws_getCoefficients(ColorSpace), Range, sws_getCoefficients(ColorSpace), Range, 0, 1<<16, 1<<16);
 
 	if(sws_init_context(Context, 0, 0) < 0){
 		sws_freeContext(Context);
@@ -131,6 +123,13 @@ int GetPPCPUFlags() {
 }
 
 
+int GetSwsAssumedColorSpace(int W, int H) {
+	if (W > 1024 || H >= 600)
+		return SWS_CS_ITU709;
+	else
+		return SWS_CS_DEFAULT;
+}
+
 
 
 /***************************
@@ -222,12 +221,12 @@ static int GetPseudoDepth(const AVPixFmtDescriptor &Desc) {
 }
 
 static LossAttributes CalculateLoss(PixelFormat Dst, PixelFormat Src) {
-    const AVPixFmtDescriptor &SrcDesc = av_pix_fmt_descriptors[Src];
-    const AVPixFmtDescriptor &DstDesc = av_pix_fmt_descriptors[Dst];
+	const AVPixFmtDescriptor &SrcDesc = av_pix_fmt_descriptors[Src];
+	const AVPixFmtDescriptor &DstDesc = av_pix_fmt_descriptors[Dst];
 	BCSType SrcCS = GuessCSType(Src);
 	BCSType DstCS = GuessCSType(Dst);
 
-    LossAttributes Loss;
+	LossAttributes Loss;
 	Loss.Format = Dst;
 	Loss.DepthDifference = GetPseudoDepth(DstDesc) - GetPseudoDepth(SrcDesc);;
 	Loss.ChromaOversampling = FFMAX(0, SrcDesc.log2_chroma_h - DstDesc.log2_chroma_h) + FFMAX(0, SrcDesc.log2_chroma_w - DstDesc.log2_chroma_w); 
@@ -261,13 +260,10 @@ PixelFormat FindBestPixelFormat(const std::vector<PixelFormat> &Dsts, PixelForma
 	std::vector<PixelFormat>::const_iterator i = std::find(Dsts.begin(), Dsts.end(), Src);
 	if (i != Dsts.end())
 		return Src;
-	//
-
-	const AVPixFmtDescriptor &SrcDesc = av_pix_fmt_descriptors[Src];
 
 	i = Dsts.begin();
 	LossAttributes Loss = CalculateLoss(*i++, Src);
-	for (; i != Dsts.end(); i++) {
+	for (; i != Dsts.end(); ++i) {
 		LossAttributes CLoss = CalculateLoss(*i, Src);
 		if (Loss.CSLoss == 3 && CLoss.CSLoss < 3) { // Preserve chroma information at any cost
 			Loss = CLoss;
diff --git a/src/core/videoutils.h b/src/core/videoutils.h
index 0dc79f0..52f5aae 100644
--- a/src/core/videoutils.h
+++ b/src/core/videoutils.h
@@ -39,8 +39,9 @@ extern "C" {
 
 // swscale and pp-related functions
 int64_t GetSWSCPUFlags();
-SwsContext *GetSwsContext(int SrcW, int SrcH, PixelFormat SrcFormat, int DstW, int DstH, PixelFormat DstFormat, int64_t Flags, int ColorSpace = -1);
+SwsContext *GetSwsContext(int SrcW, int SrcH, PixelFormat SrcFormat, int DstW, int DstH, PixelFormat DstFormat, int64_t Flags, int ColorSpace = SWS_CS_DEFAULT, int ColorRange = -1);
 int GetPPCPUFlags();
+int GetSwsAssumedColorSpace(int Width, int Height);
 
 // timebase-related functions
 void CorrectNTSCRationalFramerate(int *Num, int *Den);
diff --git a/version.sh b/version.sh
index f6bfb62..47fed12 100755
--- a/version.sh
+++ b/version.sh
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 strip_echo () {
-    echo -n $(echo -n "$@" | tr -d '\n')
+    printf '%s' "$(echo "$@" | tr -d '\n')"
 }
 
 echo_maybe () {

-- 
ffms2 packaging



More information about the pkg-multimedia-commits mailing list